Django Notes

I wanted to read about what all Django has to offer since I have never used it before.

1 43

Django Notes

References

Notes

Django makes it easier to build better web apps more quickly and with less code.

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. It's free and open source.

Django comes with a object-relational mapper in which you describe your database layout in Python code. The data-model syntax offers many rich ways of representing your models - so far, it has been solving many years' worth of database-schema problems. An example:

from django.db import models


class Reporter(models.Model):
    full_name = models.CharField(max_length=70)

    def __str__(self):
        return self.full_name


class Article(models.Model):
    pub_date = models.DateField()
    headline = models.CharField(max_length=200)
    content = models.TextField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

    def __str__(self):
        return self.headline

Next, run the Djano command-line utilities to create the database tables automatically:

$ python manage.py makemigrations
$ python manage.py migrate

The makemigrations command looks at all of the availble models and creates migrations for whichever tables don't already exist. migrate runs the migrations and creates tables in your database, as well as optionally proving much richer schema control. With that, you've got a free and rich Python API to access your data. The API is created on the fly, no code generation necessary. Once your models are defined, Django can automatically create a professional, production ready administrative interface - a website that lets authenticated users add, change and delete objects.

To design URLs for an app, you create a Python module called a URLconf. A table fo contents for your app, it contains a mapping between URL patterns and Python callback functions. URLconfs also serve to decouple URLs from Python code. Example:

from django.urls import path

from . import views

urlpatterns = [
    path("articles/<int:year>/", views.year_archive),
    path("articles/<int:year>/<int:month>/", views.month_archive),
    path("articles/<int:year>/<int:month>/<int:pk>/", views.article_detail),
]

The code maps URL paths to Python callback functions ("views"). The path strings are parameter tags to "capture" values from the URLs. When a user requests a page, Django runs through each path, in order, and stops at the first one that matches the requested URL. The paths are compiled into regular expressions at load time.

Models

A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you're storing. Generally, each model maps to a single database table. Each model is a Python class that subclasses django.db.models.Model. Each attribute of the model represents a database field. With all of this, Django gives you automatically-generated database-access API.

Example

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
CREATE TABLE myapp_person (
    "id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL
);

Using Models

The name of the table os derived from some model metadata but can be overridden. The id field is added automatically, but this can be overridden. Django uses SQL tailored to your database backend specified in your settings file. Once you have defined your models, you need to tell Django you're going to use those models. Do this by editing your settigs file and changing the INSTALLED_APPS setting to add the name of the module that contains your models.py. When you add new apps to INSTALLED_APPS, make sure to run manage.py migrate.

Fields

The modt important and only required part of a model is the list of database fields it defines. Fields are specified by class attributes. Be careful to not choose field names that conflict with the models API like clean, save, or delete.

Example

from django.db import models

class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)

class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()

Field Types

Each filed should be an instance of the appopriate Field class. The field class type determines the column type, the default HTML widget to use when rendering the form field, and the minimum validation requirements. Complete List of Built-In Field Types. You can also create custom model fields. Each field takes a certain set of field-specific arguments (documented in the model field reference).

Relationships

Django offers ways to define the three most common relationships: man-to-one, many-to-many, and one-to-one.

You can give your model metadata by using class Meta. You can define custom methods on a model to add custom "row-level" functionality to your objects. Whereas Manager methods are intended to do "table-wide" things, model methods should act on a particular model instance. This is a valuable technique for keeeping business logic in one place - the model.

Making Queries

Once you've created your data models, Django automatically gives you a database-abstraction API that lets you create, update, and delete objects. A model class represents a database table, and an instance of that class represents a particular record in the database table. To create an object, instantite it using the keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT behind the scenes. To save changes to an object that's already saved in the database, use save().

To retrieve objects from your database, construct a QuerySet via a Manager on your model class. A QuerySet represents a collection of objects from your database. It can have zero, one, or many filters. Filters narrow down the query results based on the given parameters. In SQL terms, a QuerySet equates to a SELECT statement, and a filter is a limiting clause such as WHERE or LIMIT. The Manager is the main source of query sets for a model. The all() mthod returns a QuerySet of all the objects in the database.

all_entries = ModelName.objects.all()

To create a subset of of rows to return, you refine the initial QuerySet, adding filter conditions. The two most common ways to refine a QuerySet are: filter, which contains objects that match the given lookup parameters, and exclude, which returns a new QuerySet containing objects that do not match the given lookup parameters. The result of refining a QuerySet is itself a QuerySet, so it is possible to chain refinements together.

ModelName.objects.filter(headline__startswith="What").exclude(
  pub_date__gte=datetime.date.today()
).filter(pub_date__gte=datetime.date(2005, 1, 30))

QuerySet objects are lazy - the act of creating a QuerySet doesn't involve any database activity. Django won't actually run the query until the QuerySet is evaluated. In general, the results of a QuerySet aren't fetched from the database until you ask for them. When you do, the QuerySet is evaluated by accessing the database. If you know there is only one object that matches your query, you can use the get() mthod on the manager which returns the object directly. You can use a subset of Python's array-slicing syntax to limit your QuerySet to a certain number of results. Generally, slicing a QuerySet returns a new QuerySet - it doesn't evaluate the query. Field Lookup Reference. You can generate aggregates over a QuerySet.

A Manager is an interface through which database query operations are provided to the Django models. Django gives you some ways of performing raw SQL queries. Django gives you a few ways to control how database transactions are managed.

How Django Processes a Request

When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute:

  1. Django determines the root URL conf module to use. This is the value of the ROOT_URLCONF setting usually.
  2. Django loads that Python module and looks for the variable urlpatterns. sThis should be a sequence of django.urls.path() and/or django.urls.re_path() instances.
  3. Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info.
  4. Once one of the URL patterms matches, Django imports and calls the given view, which is a Python function. The view gets passed some parguments.
  5. If no URL pattern matches, or if an exception is raised during any point in this process, Django invokes an appropriate error-handling view.

Example

from django.urls import path

from . import views

urlpatterns = [
    path("articles/2003/", views.special_case_2003),
    path("articles/<int:year>/", views.year_archive),
    path("articles/<int:year>/<int:month>/", views.month_archive),
    path("articles/<int:year>/<int:month>/<slug:slug>/", views.article_detail),
]

Writing Views

A view function, or view for short, is a Python function that takes a web request and returns a web response. This reponse can be the HTML contents of a webpage, or a redirection, or a 404 error, or an XML document, or an image - anything. The view itself contains whatever arbitrary logic is necessary to return that response. This code can live anywhere you want, as long as it's on your Python path.

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = '<html lang="en"><body>It is now %s.</body></html>' % now
    return HttpResponse(html)

Django provides several decorators that can be applied to views to support various HTTP features. When Djano handles a file upload, the file data ends placed in request.FILES. The package django.shortcuts collects helper functions and classes that “span” multiple levels of MVC. In other words, these functions/classes introduce controlled coupling for convenience’s sake.

Middleware is a framework of hooks into Django's request/response processing. It's a light, low-level "plugin" system for globally altering Django's input or output. Each middleware component is responsible for doing some specific function. Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contain a session ID – not the data itself. Django provides a range of tools and libraries to help you build forms to accept input from site visitors, and then process and respond to the input. A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid. Being a web framework, Django needs a convenient way to generate HTML dynamically. The most common approach relies on templates. A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted.

Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They’re designed to be mostly automatic, but you’ll need to know when to make migrations, when to run them, and the common problems you might run into. Django has an authentication system. Django has a cacheing framework. Django provides some tooling for sending emails. A Django settings file contains all the configuration of your Django installation. Django includes a “signal dispatcher” which helps decoupled applications get notified when actions occur elsewhere in the framework. In a nutshell, signals allow certain senders to notify a set of receivers that some action has taken place.

You can read more about how comments are sorted in this blog post.

User Comments