and also Django Rest Framework

Django and Django Rest Framework

Shaphil Mahmud
2 min readSep 2, 2019

--

Tips and Tricks related to Django and DRF

DRF — Accessing Request User from Serializers

The request.user is not directly available from 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, just add that to thevalidated_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—

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.

https://docs.djangoproject.com/en/2.2/ref/models/options/#verbose-name-plural

Source — https://leanpub.com/tangowithdjango19/

--

--

Shaphil Mahmud

Fullstack Software Engineer. Lover of the backend. Friends with the Frontend. https://shaphil.me