Frequently asked questions

Django

How can I return documents such as zip or pdf as file downloads in Django?

All libraries that operate on file objects such as zipfile or reportlab will also work work with file-like objects. If you dynamically generate such an object you create a buffer instance and then use django's FileResponse to return a file-like object.

import io
from django.http import FileResponse
from reportlab.pdfgen import canvas

def my_view(request):
    buffer = io.BytesIO()
    c =  canvas.Canvas(buffer)
    c.drawString(100, 100, "Hello world.")
    c.showPage()
    c.save()
    buffer.seek(0)
    return FileResponse(buffer, as_attachment=True, filename='hello.pdf')

For more details see the official django documentation

How do I automatically set the creation date in a model field?

Set the auto_now_add parameter to True. In this case the field value is only set when the record ist created and does not get changed on updates. If you want to keep track of when the record has last been updated you must use auto_now.

created = models.DateField(auto_now_add=True)
last_modified = models.DateField(auto_now=True)

How do I output a formatted date in a Django template?

Use the "date" filter:

<p class="tag is-info">Published: {{article.created|date:"d/m/Y"}}</p>

I get a "TemplateNotFound" error. I have checked folder structure and path to template in views.py and everything looks fine!

You probably have just created a new app within your project but forgot to register the app in settings.py. Add your app to INSTALLED_APPS like so:

INSTALLED_APPS = [
    'mynewapp.apps.MynewappConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]