Categories
Python Answers

How to show Image from Imagefield with Python Django Admin?

To show Image from Imagefield with Python Django Admin, we can add our own tag.

For instance, w write

def image_tag(self):
    from django.utils.html import escape
    return u'<img src="%s" />' % escape(<URL to the image>)
image_tag.short_description = 'Image'
image_tag.allow_tags = True

to add the image_tag that returns a string with the img element.

Then in admin.py, we reguister the tag with

fields = ( 'image_tag', )
readonly_fields = ('image_tag',)
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.