Skip to the content.

Django

Django Architecture

This is how Django handles HTTP requests and generates responses:

  1. A web browser requests a page by its URL and the web server passes the HTTP request to Django.
  2. Django runs through its configured URL patterns and stops at the first one that matches the requested URL.
  3. Django executes the view that corresponds to the matched URL pattern.
  4. The view potentially uses data models to retrieve information from the database.
  5. Data models provide data definitions and behaviors. They are used to query the database.
  6. The view renders a template (usually HTML) to display the data and returns it with an HTTP response.

Django Project Layout

When QuerySets are evaluated

Creating a QuerySet doesn’t involve any database activity until it is evaluated. QuerySets will usually return another unevaluated QuerySet. You can concatenate as many filters as you like to a QuerySet, and you will not hit the database until the QuerySet is evaluated. When a QuerySet is evaluated, it translates into a SQL query to the database.

QuerySets are only evaluated in the following cases:

Django template dot notation lookup

Technically, when the template system encounters a dot, it tries the following lookups, in this order:

Django-taggit

from taggit.managers import TaggableManager

class MyModel(models.Model):

    # ...
    tags = TaggableManager()  # Creates an Model manager.

my_model_obj = MyModel.objects.get(id=1)
my_model_obj.tags.add("music", "jazz", "django")  # Adds the tags
my_model_obj.all()  # Gets all tags associated to the object.
my_model_obj.remove("django")  # removes the tag associated to the object.

Creating custom template tags and filters

Django offers a varietry of built-in template tags, such as {% load %} or {% block %}. similary Django allows you to create your own template tags to perform custom actions.

Django Provides 2 helper functions, which allow you to easily create template tags.

Custom Template tags should be created in the Django’s application /templatetags package.

from django import template

regiser = template.Library()

@register.simple_tag(name="my_tag")
def func():
  ...

@register.inclusion_tag(filename="blog/post/latest_posts.html", name="my_inclusion_tag")
def inc_func():
  ...

Implementing Custom Filters

Django has a variety of built-in template filters that allow you to alter variables in templates. There are Python functions that take one or more parameters, the value of the variable that the filter is applied to, and an optional argument. They return a value that can be displayed or treated by another filter.

Adding Sitemaps to the Site