Tips and Tricks — Django and Django REST Framework
These tips may or may not be common. For me, they weren’t but helped me in tricky situations.
Tips and Tricks related to Django and DRF
DRF — Accessing Request User from Serializers
The request.user
is not directly available to serializers. You have to fetch the User
from the request
object available through context
.
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
Source — https://stackoverflow.com/a/30203950/5341284
DRF — Add additional data through Serializers
To add some extra information during object creation through serializers, add that to the validated_data
dictionary.
class MySerializer(serializers.ListSerializer):
def create(self, validated_data):
validated_data['user'] = user
Django — Hash and upload
To rename an uploaded file to its hash
import os
import hashlib
from functools import partial
def hash_file(file, block_size=65536):
md5sum = hashlib.md5()
for buf in iter(partial(file.read, block_size), b''):
md5sum.update(buf)
return md5sum.hexdigest()
def hash_and_upload(instance, filename):
instance.image.open()
name, ext = os.path.splitext(filename)
return '{0}{1}'.format(hash_file(image), ext)
# models.py
class Picture(models.Model):
image = models.ImageField(upload_to=hash_and_upload)
Sources-
- https://docs.djangoproject.com/en/2.2/ref/models/fields/#filefield
- https://gist.github.com/Alir3z4/725297248a59cae05a50b15dd79fb4d0
Django — Pluralize model names
To specify a model’s name in plural, define the Meta class field verbose_name_plural
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
class Meta:
verbose_name_plural = 'Categories'
Django admin usually pluralizes the model name by appending an “s” to it. So in this case, if you don’t define the meta field the model will show up in the Admin as Categorys
which is something you probably won't want.
Source — https://docs.djangoproject.com/en/3.1/ref/models/options/#verbose-name-plural
Originally published at https://blog.shaphil.me on August 19, 2020.