Search code snippets, questions, articles...

django code snippets

Django: How to Delete All Rows from a Table
Student.objects.all().delete()
Encrypt a password field in Django models
from django.contrib.auth.hashers import make_password

class Student(models.Model):
    s_name = models.CharField(max_length=50, null=False)
    s_password = models.CharField(max_length=30, null=False)

    def save(self, *args, **kwargs):
        self.s_password = make_password(self.s_password)
        super(Student, self).save(*args, **kwargs)
Create a password field in Django model
# models.py
from django import models

class Student(models.Model):
    username = models.CharField(max_length=60)
    password = models.CharField(max_length=30)


# forms.py
from django import forms

class StudentForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = Student
Django Translation
# Update the .po file , exclude the venv file
django-admin makemessages -l tr -i venv

# Compile the messages 
django-admin compilemessages
Django bulk get or create
IntegrationRequirement.objects.bulk_create(objs=objs, ignore_conflicts=True)
get_or_create()
try:
    obj = Person.objects.get(first_name='John', last_name='Lennon')
except Person.DoesNotExist:
    obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
    obj.save()

#shortcut for the above code

obj, created = Person.objects.get_or_create(
    first_name='John',
    last_name='Lennon',
    defaults={'birthday': date(1940, 10, 9)},
)
Django update model with for loop
def update(self, instance, validated_data):
    for attr, value in validated_data.items():
        setattr(instance, attr, value)
    instance.save()
    return instance
Django send post request with different field than primary key.
class ContactCompanySerializer(serializers.ModelSerializer):
    # profile=ProfileSerializer()
    # array şeklinde gönderiyoruz. Array içindekiler de charfield yani string.
    integration_requirements = serializers.ListSerializer(
        child=serializers.CharField())

    class Meta:
        model = ContactCompany
        fields = ('id', 'name', 'website', 'country', 'city',
                  'address', 'sector', 'note', 'profile',
                  'integration_requirements')
        # exclude_fields = ('created_at', 'updated_at', 'is_active')
    
    # create methodunu override ediyoruz.
    def create(self, validated_data):
        # integration requirements kısmını validatet datadan çekiyoruz (array olarak).
        integration_requirements = validated_data.pop(
            'integration_requirements', [])
        # company objemizi oluÅŸturuyoruz ve IntegrationRequirement modelinden
        # post requestte gönderdiğimiz requirementleri filtreliyoruz.
        company = super().create(validated_data)
        integration_requirements_qs = IntegrationRequirement.objects.filter(
            requirement__in=integration_requirements)
        # Company'e direkt olarak requirementsleri ekliyoruz.
        company.integration_requirements.add(*integration_requirements_qs)
        return company
Django Rest Framework field level serializer validation.
from rest_framework import serializers

class BlogPostSerializer(serializers.Serializer):
    title = serializers.CharField(max_length=100)
    content = serializers.CharField()

    def validate_title(self, value):
        """
        Check that the blog post is about Django.
        """
        if 'django' not in value.lower():
            raise serializers.ValidationError("Blog post is not about Django")
        return value
Add accept range header to play mp4 file on IOS devices in Django
import os
import re
import mimetypes
from wsgiref.util import FileWrapper

from django.http.response import StreamingHttpResponse

range_re = re.compile(r'bytess*=s*(d+)s*-s*(d*)', re.I)

class RangeFileWrapper(object):
    def __init__(self, filelike, blksize=8192, offset=0, length=None):
        self.filelike = filelike
        self.filelike.seek(offset, os.SEEK_SET)
        self.remaining = length
        self.blksize = blksize

    def close(self):
        if hasattr(self.filelike, 'close'):
            self.filelike.close()

    def __iter__(self):
        return self

    def __next__(self):
        if self.remaining is None:
            # If remaining is None, we're reading the entire file.
            data = self.filelike.read(self.blksize)
            if data:
                return data
            raise StopIteration()
        else:
            if self.remaining <= 0:
                raise StopIteration()
            data = self.filelike.read(min(self.remaining, self.blksize))
            if not data:
                raise StopIteration()
            self.remaining -= len(data)
            return data


def stream_video(request, filename):
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    file_path = os.path.join(BASE_DIR, "app_name/static/video/" + filename)

    range_header = request.META.get('HTTP_RANGE', '').strip()
    range_match = range_re.match(range_header)
    size = os.path.getsize(file_path)
    content_type, encoding = mimetypes.guess_type(file_path)
    content_type = content_type or 'application/octet-stream'
    if range_match:
        first_byte, last_byte = range_match.groups()
        first_byte = int(first_byte) if first_byte else 0
        last_byte = int(last_byte) if last_byte else size - 1
        if last_byte >= size:
            last_byte = size - 1
        length = last_byte - first_byte + 1
        resp = StreamingHttpResponse(RangeFileWrapper(open(file_path, 'rb'), offset=first_byte, length=length), status=206, content_type=content_type)
        resp['Content-Length'] = str(length)
        resp['Content-Range'] = 'bytes %s-%s/%s' % (first_byte, last_byte, size)
    else:
        resp = StreamingHttpResponse(FileWrapper(open(file_path, 'rb')), content_type=content_type)
        resp['Content-Length'] = str(size)
    resp['Accept-Ranges'] = 'bytes'
    return resp
Allow or limit a view to superuser only Django
from django.contrib.auth.decorators import user_passes_test

@user_passes_test(lambda u: u.is_superuser)
def dashboard(request):
    return "View"
Create or save object data in Django
//ONE LINE SYNTAX TO SAVE DATA 
person = Person.objects.create(first_name="John", last_name="Deo")


//YOU CAN ALSO USE BELOW CODE TO SAVE DATA
person = Person(first_name="John", last_name="Deo")
person.save()
Retrieving all objects in Django
all_entries = Entry.objects.all();
Database migration commands in django
//TO CREATE MIGRATIONS
python manage.py makemigrations

//TO APPLY MIGRATIONS
python manage.py migrate
Django runserver command
python manage.py runserver 9090
Create models in Django
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=30)
    experience = models.IntegerField()
    is_active = models.BooleanField()
    auto_field = models.AutoField() //INTEGER FIELD THAT automatically increments
    emaill = models.EmailField(max_length=100) //CharField that checks - provided value is a valid email
    description = models.TextField() //Used to store large text value
    created_date = models.DateTimeField()
Django template loop n times
//CODE FOR VIEW
render(request, 'page.html', {'range': range(10)}) // TO START RANGE FROM ONE use range(1,11)


//CODE FOR TEMPLATE
{% for i in range %}
     ...
{% endfor %}