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