Skip to content

Intro

Django Advanced Topic

Django is a robust and feature-rich framework that provides many advanced features for building complex web applications. Below are some of the advanced topics in Django, including signals and channels, as well as others like middleware, forms, custom model managers, and more.

Advanced Topics in Django

  1. Django Signals

    • Overview: Signals are a way to allow decoupled applications to get notified when certain events occur elsewhere in the application.
    • Common Use Cases: User creation, email notifications, logging.
    • Example:
    # signals.py
      from django.db.models.signals import post_save
      from django.dispatch import receiver
      from django.contrib.auth.models import User
      from .models import Profile
    
      @receiver(post_save, sender=User)
      def create_profile(sender, instance, created, **kwargs):
          if created:
              Profile.objects.create(user=instance)
    
      @receiver(post_save, sender=User)
      def save_profile(sender, instance, **kwargs):
          instance.profile.save()
    
  2. Django Channels

    • Overview: Extends Django to handle WebSockets, HTTP2, and other protocols that require long-lived connections.
    • Common Use Cases: Real-time chat applications, notifications, live updates.
    • Example: Refer to the previous example on WebSockets for setting up real-time notifications with Django Channels.
  3. Middleware

    • Overview: Middleware is a way to process requests globally before they reach the view or after the view has processed them.
    • Common Use Cases: Authentication, logging, request modification.
    • Example:
    # middleware.py
    class SimpleMiddleware:
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
            # Code to be executed for each request before the view (and later middleware) are called.
            response = self.get_response(request)
            # Code to be executed for each request/response after the view is called.
            return response
    
  4. Custom Model Managers

    • Overview: Managers are the interface through which database query operations are provided to Django models.
    • Common Use Cases: Adding extra manager methods, customizing queryset behavior.
    • Example:
    from django.db import models
    
    class PublishedManager(models.Manager):
        def get_queryset(self):
            return super().get_queryset().filter(status='published')
    
    class Post(models.Model):
        STATUS_CHOICES = (
            ('draft', 'Draft'),
            ('published', 'Published'),
        )
        title = models.CharField(max_length=200)
        status = models.CharField(max_length=10, choices=STATUS_CHOICES)
    
        objects = models.Manager()  # The default manager.
        published = PublishedManager()  # Our custom manager.
    
  5. Custom Forms and Formsets

    • Overview: Django forms handle user input and validation. Formsets allow handling multiple forms on a single page.
    • Common Use Cases: Complex form processing, multiple related forms.
    • Example:
    from django import forms
    from .models import Post
    
    class PostForm(forms.ModelForm):
        class Meta:
            model = Post
            fields = ['title', 'content']
    
    from django.forms import formset_factory
    PostFormSet = formset_factory(PostForm, extra=2)
    
  6. Custom Template Tags and Filters

    • Overview: Template tags and filters allow custom functionalities in Django templates.
    • Common Use Cases: Custom formatting, reusable template logic.
    • Example:
    # templatetags/custom_tags.py
    from django import template
    
    register = template.Library()
    
    @register.filter(name='cut')
    def cut(value, arg):
        return value.replace(arg, '')
    
    @register.simple_tag
    def current_time(format_string):
        return datetime.datetime.now().strftime(format_string)
    

Reference