Categories
Python Answers

How to create a file and save it to a model’s FileField with Python Django?

To create a file and save it to a model’s FileField with Python Django, we can open the file with open.

And then we can call save with the file.

For instance, we write

from django.core.files.base import File

with open('/path/to/file') as f:
    self.license_file.save(new_name, File(f))

to open the file at the given path with open.

Then we create File object with file handle f.

And then we call save with the file name and the File object we created.

We can also use ContentFile if we want to create a file without opening a file.

For instance, we write

from django.core.files.base import ContentFile

self.license_file.save(new_name, ContentFile('A string with the file content'))

to create a ContentFile with a string and save it by calling save with the file name and the ContentFile.

Categories
Python Answers

How to perform HTML decoding/encoding using Python Django?

To perform HTML decoding/encoding using Python Django, we can use escape and unescape.

For instance, we write

from html import escape

print(escape("<"))

to escape the '<' string.

And we reverse the escaping with

from html import unescape  

print(unescape("&gt;"))

to call unescape to unescape the "&gt;" string.

Categories
Python Answers

How to filter a date of a DateTimeField in Python Django?

To filter a date of a DateTimeField in Python Django, we can use filter with a datetime.

For instance, we write

YourModel.objects.filter(datetime_published=datetime(2018, 03, 27))

to call filter to return the results with the datetime_published field set to 2018-03-27.

Categories
Python Answers

How to do Summation of Multiplication of two fields with Python Django Aggregation?

To do summation of multiplication of two fields with Python Django aggregation, we can call the aggergrate method.

For instance, we write

from django.db.models import F

Task.objects.aggregate(total=Sum(F('progress') * F('estimated_days')))['total']

to call aggregate to use Sum and F to sum up the progress multiplied by the estimated_days values.

And then we get the total value from the aggregation to return the value.

Categories
Python Answers

How to download a file with Python Django?

To download a file with Python Django, we can return a response with the download file.

For instance, we write

import os
from django.conf import settings
from django.http import HttpResponse, Http404

def download(request, path):
    file_path = os.path.join(settings.MEDIA_ROOT, path)
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
            response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
            return response
    raise Http404

to create the download view that gets the file from file_path if it exists.

We call open to open the file.

And the we create a HttpResponse with the Content-Disposition header set.

We set the content_type when we create the HttpResponse to the MIME type of the file downloaded.

And fh.read() has the download file content.

Then we return the response.

If the file isn’t found, then we return a 404 error with raise Http404.