django

Synopsis

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design that follows the model–template–views architectural pattern (MVT).

Django CLI Commands

CommandDescription
django-admin startproject project-nameTo create a new project
django-admin startapp app-nameTo create a new app
python manage.py makemigrationsTo update changes to models
python manage.py migrateTo store migrations
python manage.py runserver [addrport]To run server
python manage.py shellTo invoke the Python shell
python manage.py createsuperuserTo create a superuser
python manage.py testTo run tests
python manage.py flushTo removes all data from the database and re-executes any post-synchronization handlers
python manage.py collectstaticTo collect staticfiles into a separate folder
python manage.py changepassword To change username’s password
python manage.py helpTo list all the custom or existing command of all installed apps
python manage.py dbshellTo run SQL queries
python manage.py sendtestemail [email [email …]]To send a test email (to confirm email sending through Django is working) to the recipient(s) specified
python manage.py inspectdb [table [table …]]To introspect the database tables in the database pointed-to by the NAME setting and outputs a Django model module (a models.py file) to standard output
python manage.py createcachetableTo Creates the cache tables for use with the database cache backend using the information from your settings file

Django Model Layer

CodeDescription
from django.db import modelsImports the models module, which contains models.Model class
models.ModelThe base class for django models
models.ForeignKey()To define a many-to-one relationship
models.ManyToMany()To define a many-to-many relationship
models.OneToOneField()To define an extension of a model
on_delete=models.CASCADECascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey
on_delete=models.PROTECTPrevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError
on_delete=models.RESTRICTPrevent deletion of the referenced object by raising RestrictedError (a subclass of django.db.IntegrityError)
on_delete=models.SET_NULLSet the ForeignKey null; this is only possible if null is True
on_delete=models.SET_DEFAULTSet the ForeignKey to its default value; a default for the ForeignKey must be set
on_delete=models.SET()Set the ForeignKey to the value passed to SET(), or if a callable is passed in, the result of calling it
object = Object.objects.create()To create an instance of the model
object.save()To save the object in db
object.update()To update changes of the object in db
object.delete()To delete the object from db
query = Object.objects.get()To query the model

Django View Layer

CodeDescription
from django.urls import pathURL conf
urlpatterns = [path(‘blog/’, views.page)]Map functions to urls
from django.urls import includeInclude other URLconf modules
urlpatterns = [path(‘community/’, include(‘aggregator.urls’))]Exemple of include usage
render()django.shortcuts: render(request, template_name, context=None, content_type=None, status=None, using=None)
redirect()django.shortcuts: redirect(to, *args, permanent=False, **kwargs)
get_object_or_404()django.shortcuts: Calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception
get_list_or_404()django.shortcuts: Returns the result of filter() on a given model manager cast to a list, raising Http404 if the resulting list is empty
HttpResponse(html)from django.http import HttpResponse
HttpResponseNotFound(html)django.http.Http404
JsonResponse()django.http: An HttpResponse subclass that helps to create a JSON-encoded response. It inherits most behavior from its superclass with a couple differences
StreamingHttpResponse()django.http: stream chunks of data. Useful for generating large csv files
FileResponse()django.http: FileResponse is a subclass of StreamingHttpResponse optimized for binary files

Django Template Layer

Variables

Variables are surrounded by {{ and }}:

<p>User name is {{ user_name }}. User age is {{ user_age }}.</p>

Tags Tags provide arbitrary logic in the rendering process Tags are surrounded by {% and %}:

{% if condition %}

<p>hello</p>
{% endif %}

Filters

Filters transform the values of variables and tag arguments:

Add 3 to the value of an integer:

{{ int_value | "add: 3" }}

Capitalize the first letter of the string:

{{ text_value | capfirst }}

Format a date:

{{ date_value | date:"D d M Y" }}

Comments

Comments are surrounded by {# and #}

{# This is a comment #}

A {% comment %} tag provides multi-line comments.

{% comment %}
Comment 1
Comment 2
Comment 3
{% endcomment %}