Django Flashcards
structure of newly created project mysite
mysite/ manage.py mysite/ \_\_init\_\_.py settings.py urls.py wsgi.py
manage.py - command line utility to interact with your project
__init__.py - empty file that tell python treat mysite directory as Python module
settings.py This indicates settings and configuration for your project and contains initial default settings.
urls.py This is the place where your URL patterns
live. Each URL defined here is mapped to a view.
wsgi.py This is the configuration to run your project as a Web Server Gateway Interface (WSGI) application.
Start the development server by typing the following command from your project’s root folder:
python manage.py runserver
DEBUG in settings
is a boolean that turns the debug mode of the project on and off.
ALLOWED_HOSTS in settings
is not applied while debug mode is on, or when
the tests are run. Once you move your site to production and set DEBUG to False , you will have to add your domain/host to this setting in order to allow it to serve your Django site.
INSTALLED_APPS in settings
is a setting you will have to edit for all projects.
This setting tells Django which applications are active for this site. By default, Django includes the following
applications:
django.contrib.admin - An administration site
django.contrib.auth - An authentication framework
django.contrib.contenttypes - a framework for handling contenttypes
django.contrib.sessions - a session framework
django.contrib.messages - a messaging framework
django.contrib.staticfiles - a framework for managing static files
MIDDLEWARE in settings
is a list containing middleware to be executed
ROOT_URLCONF in settings
indicates the Python module where the root URL patterns of your application are defined.
DATABASES in settings
is a dictionary that contains the settings for all the
databases to be used in the project. There must always be a default database. The default configuration uses an SQLite3 database.
LANGUAGE_CODE in settings
defines the default language code for django site
USE_TZ in settings
Django to activate/deactivate timezone support.
Django comes with support for timezone-aware
datetime. This setting is set to True when you create a new project using the startproject management command.
What is applications and projects in django
In Django, a project is considered a
Django installation with some settings. An application is a group of models, views, templates, and URLs. Applications interact with the framework to provide some specific functionalities and may be reused in various projects. You can think of the project as your
website, which contains several applications such as a blog, wiki, or forum, that can be used by other projects also.
create project in django
django-admin startproject myproject
create application in django
python manage.py startapp blog
Basic structure of application
app/ \_\_init\_\_.py admin.py apps.py migrations/ \_\_init\_\_.py models.py tests.py views.py
admin.py - where you register your models to include them in admin django site
apps.py - include main configuration of app
migrations/ - contain database migrations of your application
models.py - data models of your application
tests.py - test for your application
views.py - the logic of your application goes here - each view receives HTTP request, process it and return response
In order for Django to keep track of our application and be able to create database tables for its models, we have to activate it. To do this
edit the settings.py file and add blog.apps.BlogConfig to the INSTALLED_APPS setting.
to create an initial migration for our Post model of blog application. In the root directory of your project, run the following command:
python manage.py makemigrations blog
The WHAT command takes migration names and returns their SQL without executing it.
python manage.py sqlmigrate blog 0001
specify a custom database name for your model in the Meta class of the model using the WHAT attribute.
db_table
migrate to sync databases
python manage.py migrate
creating a superuser
python manage.py createsuperuser
adding model to admin site
in admin.py of application write:
from django.contrib import admin
from .models import Post
admin.site.register(Post)
Customizing the way models are displayed
in admin.py of application write:
from django.contrib import admin
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = (‘title’, ‘slug’, ‘author’, ‘publish’, ‘status’)
list_filter = (‘status’, ‘created’, ‘publish’, ‘author’)
search_fields = (‘title’, ‘body’)
prepopulated_fields = {‘slug’: (‘title’,)}
raw_id_fields = (‘author’,)
date_hierarchy = ‘publish’
ordering = (‘status’, ‘publish’)
Run shell
python manage.py shell
get method of Model.
for example:
user = User.objects.get(username=’admin’)
The get() method allows you to retrieve a single object from the database. Note that this method expects a result that matches the query. If no results are returned by the database, this method will raise a DoesNotExist exception, and if the database returns more than one result, it will raise a MultipleObjectsReturned exception.
create a db Post and save it to database
post = Post(title=’Another post’, slug=’another-post’, body=’Post body.’)
post.save()
and in a single operation:
Post.objects.create(title=’One more post’, slug=’one-more-post’, body=’Post body.’)
A QuerySet is
a collection of objects from your database that can have several filters to limit the results.
To retrieve all objects from a model Post
all_posts = Post.objects.all()
retrieve all posts published in the year 2017 using the QuerySet
Post.objects.filter(publish__year=2017)
retrieve all posts published in 2017 by the author with the username admin
Post.objects.filter(publish__year=2017, author__username=’admin’)
or
Post.objects.filter(publish__year=2017) \
.filter(author__username=’admin’)
Queries with field lookup methods are built using two underscores, for example,
publish__year , but the same notation is also used for accessing fields of related models, such as author__username .
You can exclude certain results from your QuerySet using the exclude() method of the manager. For example, we can retrieve all posts published in 2017 whose titles don’t start with Why
Post.objects.filter(publish__year=2017) \
.exclude(title__startswith=’Why’)
You can order results by different fields using the order_by() method of the manager. For example, you can retrieve all objects ordered by
their title , as follows
Post.objects.order_by(‘title’)
Ascending order is implied. You can indicate descending order with a negative sign prefix, like this
Post.objects.order_by(‘-title’)
If you want to delete an object, you can do it from the object instance using
the delete() method: post = Post.objects.get(id=1) post.delete()
QuerySets are only evaluated in the following cases
- The first time you iterate over them
- When you slice them, for instance, Post.objects.all()[:3]
- When you pickle or cache them
- When you call repr() or len() on them
- When you explicitly call list() on them
- When you test them in a statement, such as bool() , or , and , or if
the default manager of every model that retrieves all objects in the database
objects
There are two ways to add managers to your models
you can add extra manager methods or modify initial manager QuerySets
*The first method provides you with a QuerySet API such
as Post.objects.my_manager() , and the latter provides you with Post.my_manager.all() . The manager will allow us to retrieve posts using Post.published.all() .
get_queryset() method of a manager returns the
QuerySet that will be executed.
A Django view is just a
Python function that receives a web request and returns a web response
Create a view to display a list of posts
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts})
that this parameter is required by all views.
request
what returns render function of view
HttpResponse object
If using path() and converters isn’t sufficient for you, you can use
re_path() instead to define complex URL patterns with Python regular expressions.
to create view and url
- create view in views of application
- create urls.py in application folder
- add url to project:
path(‘approute/’, include(‘app.urls’, namespace=’app’)),
URL namespaces have to be unique across your entire project. URLs easily by including the namespace,
building them, for example for app blog
blog:post_list
The convention in Django is to add a WHAT method to the model that returns the canonical URL of the object.
get_absolute_url()
reverse() method that allows you to
build URLs by their name and passing optional parameters
Django has a powerful template language that allows you to specify how data is displayed. It is based on template {1}, template {2}, and template {3}
1) tags
2) variables
3) filters
Template tags control the rendering of the template and
look like
{% tag %}
Template variables get replaced with values when the
template is rendered and look like
{{ variable }}
Template filters allow you to modify variables for display
and look like
{{ variable | filter }}
{% load static %} tells Django to
load the static template tags that are provided by the django.contrib.staticfiles application.
After loading it, you are able to use the {% static %} template filter throughout this template
how pagination works
- We instantiate the Paginator class with the number of objects we want to display on each page.
- We get the page GET parameter that indicates the current page number.3. We obtain the objects for the desired page calling the page() method of Paginator .
- If the page parameter is not an integer, we retrieve the first page of results. If this parameter is a number higher than the last page of results, we will retrieve the last page.
- We pass the page number and retrieved objects to the template.
Class-based views offer advantages over function-based views for some use cases. They have the following features:
- Organizing code related to HTTP methods, such as GET, POST, or PUT , in separate methods instead of using conditional branching
- Using multiple inheritance to create reusable view classes (also known as mixins)
def post_list(request): object_list = Post.published.all() paginator = Paginator(object_list, 3) # 3 posts in each page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request, 'blog/post/list.html', {'page': page, 'posts': posts})
equivalent for class based view
class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 3 template_name = 'blog/post/list.html'
Django’s ListView generic view passes the selected page in a variable called
page_obj
Django comes with two base classes to build forms:
Form : Allows you to build standard forms
ModelForm : Allows you to build forms tied to model instances
Forms can reside anywhere in your Django project. The convention is to place them inside a
forms.py file for each application.
define the configuration of an external SMTP server by adding the following settings in the settings.py file of your project:
EMAIL_HOST: The SMTP server host; the default is localhost
EMAIL_PORT: The SMTP port; the default is 25
EMAIL_HOST_USER: Username for the SMTP server
EMAIL_HOST_PASSWORD: Password for the SMTP server
EMAIL_USE_TLS: Whether to use a TLS secure connection
EMAIL_USE_SSL: Whether to use an implicit TLS secure
connection
If you cannot use an SMTP server, you can tell Django to write emails to the console by adding the following setting to the settings.py file:
EMAIL_BACKEND=’django.core.mail.backends.console.EmailBackend’
If you don’t define the related_name attribute, Django will use the
name of the model in lowercase, followed by _set (that is, comment_set ) to name the manager of the related object back to this one.
Creating forms from models
from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body')
module is a reusable application that primarily offers you a Tag model and a manager to easily add tags to any model
django-taggit
The WHAT QuerySet returns tuples with the
values for the given fields. If pass flat=True to it to get a flat list like [1, 2, 3, …] .
values_list()
list of similar posts example
post_tags_ids = post.tags.values_list(‘id’, flat=True)
similar_posts = Post.published.filter(tags__in=post_tags_ids)\
.exclude(id=post.id)
similar_posts = similar_posts.annotate(same_tags=Count(‘tags’))\
.order_by(‘-same_tags’,’-publish’)[:4]
Django provides the following helper functions that allow you to create your own template tags in an easy manner:
simple_tag : Processes the data and returns a string
inclusion_tag : Processes the data and returns a rendered template
example of simple_tag
from django import template
from ..models import Post
register = template.Library()
@register.simple_tag def total_posts(): return Post.published.count()
example of inclusion tag
from django import template
from ..models import Post
register = template.Library()
@register.inclusion_tag('blog/post/latest_posts.html') def show_latest_posts(count=5): latest_posts = Post.published.order_by('-publish')[:count] return {'latest_posts': latest_posts}
Using a sitemap, you will help crawlers
that index your website’s content.
Django provides a SearchQuery class to
translate the terms into a search query object.
Django provides the following class-based views to deal with authentication. All of them are located in django.contrib.auth.views :
LoginView : Handles a login form and logs in a user
LogoutView: Logs out a use
Django provides the following views to handle password changes:
PasswordChangeView: Handles a form to change the user password
PasswordChangeDoneView: The success view the user is redirected to after a successful password change
Django also includes the following views to allow users to reset their password
PasswordResetView: Allows users to reset their password. It generates a one-time use link with a token and sends it to the user’s email account.
PasswordResetDoneView : Tells users that an email—including a link to reset their password—has been sent to them.
PasswordResetConfirmView : Allows users to set a new password.
PasswordResetCompleteView: The success view the user is redirected to after successfully resetting the password.
LOGIN_REDIRECT_URL:
Tells Django which URL to redirect after a successful login if no next parameter is present in the request
LOGIN_URL:
The URL to redirect the user to log in (for example,
views using the login_required decorator)
LOGOUT_URL
The URL to redirect the user to log out
The best way to check whether the current user is authenticated is by accessing its read-only
attribute
is_authenticated
If you see the logout page of the Django administration site instead of your own log out page
check the INSTALLED_APPS setting of your project and make sure that django.contrib.admin comes after YOUR application. Both templates are located in the same relative path, and the Django template loader will
use the first one it finds.
You can provide a clean_() method to any of yourform fields in order to
clean the value or raise form validation errors for a specific field
For Django to serve media files uploaded by users with the development server, add the following settings to the settings.py file of your project
MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
The static() helper function is suitable for development
but not for production use. Never serve your static files with Django in a production environment.
Django also offers a way to substitute the whole user model with your own custom model. Your user class should inherit from Django’s
AbstractUser class, which provides the full implementation of the default user as an abstract model.
Django has a built-in messages framework that allows you to
display one-time notifications to your users.
You can create new messages using the add_message() method or any of the following shortcut methods:
success(): Success messages to be displayed after an action was successful
info(): Informational messages
warning(): Something has not yet failed but may fail imminently
error(): An action was not successful, or something failed
debug(): Debug messages that will be removed or ignored in a production environment
The AUTHENTICATION_BACKENDS setting includes
the list of authentication backends for your project. By default, this setting is set as follows:
[‘django.contrib.auth.backends.ModelBackend’]
The default ModelBackend authenticates users against
the database using the user model of django.contrib.auth
An authentication backend is a class that provides the following two methods
authenticate(): It takes the request object and user credentials as parameters. It has to return a user object that matches those credentials if the credentials are valid, or None otherwise. The request parameter is an HttpRequest object, or None if it’s not provided to authenticate() .
get_user(): Takes a user ID parameter and has to return a user object.
Consider setting db_index=True for fields that you frequently query using filter() , exclude() , or order_by() .
ForeignKey fields or fields with unique=True imply the creation of an index. You can also use {2} to create indexes for multiple fields.
1) db_index=True
2) Meta.index_together
slugify function
from django.utils.text import slugify
slugify(str)
change input type in form ModelForm
class ImageCreateForm(forms.ModelForm): class Meta: model = Image fields = ('title', 'url', 'description') widgets = { 'url': forms.HiddenInput, }
A bookmarklet is a
bookmark stored in a web browser that contains JavaScript code to extend the browser’s functionality
AJAX comes from
Asynchronous JavaScript and XML
CSRF
Cross-Site Request Forgery
The Django request object provides an WHAT method that checks whether the request is being made with XMLHttpRequest , which means it is an AJAX request. This value is set in the HTTP_X_REQUESTED_WITH HTTP header, which is included in AJAX requests by most JavaScript libraries.
is_ajax()
The ContentType model has the following
fields
app_label : This indicates the name of the application the model belongs to. This is automatically taken from the app_label attribute of the model Meta options. For example, our Image model belongs to the images application.
model : The name of the model class.
name : This indicates the human-readable name of the model. This is automatically taken from the verbose_name attribute of the model Meta options.
The select_related method is for ForeignKey and OneToOne fields. It works by performing an
SQL JOIN and including the fields of the related object
in the SELECT statement.
Usage:
actions = actions.select_related(‘user’, ‘user__profile’)[:10]
Django provides several signals for models located at
django.db.models.signals . Some of these signals are as follows
pre_save and post_save are sent before or after calling the save()
method of a model
pre_delete and post_delete are sent before or after calling the delete() method of a model or QuerySet
m2m_changed is sent when a ManyToManyField on a model is changed
Django comes with a signal dispatcher that allows receiver functions to get notified when certain actions occur. Signals are very useful when you need your code to
do something every time something else happens. You can also create your own signals so that others
can get notified when an event happens.
The following are some scenarios in which Redis suits pretty well
Counting: As you have seen, it is very easy to manage
counters with Redis. You can use incr() and incrby() for
counting stuff.
Storing latest items: You can add items to the start/end
of a list using lpush() and rpush() . Remove and return the
first/last element using lpop() / rpop() . You can trim the list
length using ltrim() to maintain its length.
Queues: In addition to push and pop commands, Redis offers blocking queue commands.
Caching: Using expire() and expireat() allows you to use Redis as a cache. You can also find third-party Redis cache backends for Django.
Pub/sub: Redis provides commands for
subscribing/unsubscribing and sending messages to
channels.
Rankings and leaderboards: Redis sorted sets with
scores make it very easy to create leaderboards.
Real-time tracking: Redis’s fast I/O makes it perfect for real-time scenarios.