Django is one of the two most popular web frameworks in the python community (the other is flask). With powerful scaffolding and many out of the box components, using Django to build web applications is fast and labor-saving. However, it is just because it is so powerful that it takes a lot of effort to control it. This article will help you to get familiar with Django framework quickly by implementing a news release website, so that you can ride this fast horse and gallop on the battlefield of web development.
Tips
This article was written in Django 2. X, which was released in 3. X. After the author’s test, running Django 3. X in Python 3.7 will result in admin unable to log in. You can choose to drop to Python 3.6 or below, or install Django 2. X.
start
Django was written by Adrian holovaty and Simon Willison in the fall of 2003 and officially released in 2005. They were making a website for a news agency, rightRapid developmentIt has relatively high requirements and hopes to be able toLet non-technical people add content to the website。 Therefore, Django has two distinct characteristics:
- High emphasisReusabilityandPluggabilityWith a large number of ready-made components built in, the development efficiency is very high
- Self contained and database linkedBackground management system, able to create content while developing
Django’s name comes from guitarist Django Reinhardt, pronounced Jang Goh, but in fact Django’s mascot is a pony with wings.
In this tutorial, we will also pay tribute to the origin of Django – take you to develop a news release website, and add news from the background management system to the homepage of the website.
Preparatory knowledge
This tutorial assumes that you already know:
- Basic Python 3 language knowledge, including using PIP installation package
- Understand the basic knowledge of HTTP protocol and how the browser and server interact
Learning objectives
After reading this tutorial, you will grasp the essence of Django MTV framework:
- M (model): create data model and perform database migration
- T (template): write out the basic Django template and pass in data from the view
- V (view): Access database in view, realize business logic, render template, and access route table
Although Django still has a lot of knowledge points, understanding MTV makes it easier to learn later knowledge points.
Install Django and start scaffolding
This article assumes that you have installed Python 3 and pip, then you can use pip to install Django directly:
pip install django
#If you are using Python 3.7, install Django 2.2:
# pip install django==2.2
It’s not a good practice to install Django directly with PIP. It’s more in line with best practice to use virtual environment. In order to reduce the cognitive burden of beginners, the installation process is simplified here. Old drivers familiar with virtual environment tools such as pipenv can use it by themselves.
After Django is installed, we use the scaffold tool Django admin provided by Django to create the project:
django-admin startproject django_news
cd django_news
The generated project skeleton and the functions of each file are as follows:
django_news
├ - django_news // project global file directory
│ ├── __init__.py
│ ├── settings.py //Global configuration
│ ├ -- URLs. Py // global routing
└ -- wsgi.py // WSGI service interface
└ -- manage.py // project management script
We use manage.py to run the development server:
python manage.py runserver
Tips
Carefully, you will find a bright red prompt: you have 17 inApplied migration (s)… (n characters are omitted). Don’t worry, we will explain the details in the next steps.
According to the prompt, we can visit localhost: 8000 through the browser and see the welcome interface:
Tips
Django development server can be kept on, and the later modified code will be automatically reloaded, which is very convenient. When running other commands later, you can open another terminal (command line).
Everything is ready, the reins are in your hands!
Create the first custom Django app
As we mentioned in the previous section, Django is a heightmodularizationThe framework of. Specifically, a Django application consists of multiple sub applications, which we generally call app (note that it is not the mobile app we often say, but the abbreviation of application), as shown in the figure below.
Categories of Django app
Django app is generally divided into three categories (according to the source):
- built-in: the application of Django framework, including admin (background management), auth (identity authentication), sessions (Session Management), etc
- custom: the application used to implement our own business logic. Here we will create a news display application
- Third partyThat is to say, the number of applications provided by the community is extremely rich, and the functions cover almost all aspects, which can greatly reduce the development cost
All Django applications are in Django_ news/ settings.py OfINSTALLED_APPS
Defined in the list:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
Implement custom app
Let’s create the first custom app with the name of news:
python manage.py startapp news
The generated news application folder structure is as follows:
News // news application directory
├ - initialization module
├ - admin.py // background management configuration
├ - apps.py // application configuration
├ - migrations // database migration file directory
└ -- database migration initialization module
├── models.py //Data model
├ - tests.py // unit test
└ -- views. Py // view
At first glance, there are many files in this subdirectory! This is because Django always insistsdecoupling The principle is to reduce the coupling between the codes as much as possible, and separate the unrelated codes into multiple modules, so that the same module hasCohesion。 Believe me, wait until the back slowly familiar with, you will be familiar with each module.
In fact, the organizational structure of each Django app conforms to the MTV rule of Django – model + template + view. MTV is very similar to MVC, which you are familiar with. However, there are big differences in naming, as shown in the following table:
As we all know, view represents the business logic in Django, that is, the controller in MVC!
Add custom app to global configuration
Finally, we add the news application to settings.pyINSTALLED_APPS
Medium:
# ...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'news',
]
So far, we have created the first Django application! But now there is no content in this application, we will gradually improve this application.
Understanding view: writing business logic
You may have noticed that you can access the background management system by visiting localhost: 8000 / Admin (although you will jump to the login interface). Next, we also want to be able to access the news application we just created. Therefore, in this step, we will:
- Write a little business logic in the view
- Access routes, enabling them to be accessed
Django’s routing system
Django’s routing system consists ofGlobal routingandSubapplication routingform. In short, according to the URL entered by the user, the global routing table matches and selects the correct sub application route, and then the selected sub application route matches and selects the correct view. The whole process is as follows:
For example, the user accesses example.com/apple/buy, and then the global route selects the route table of Apple according to / apply / buy, and then selects / buy route according to / buy from the route table of apple, and then executes the buyview view corresponding to / buy to return the result to the user.
Write the first view
After we have a general understanding of the process of view access, we can start. First, open news / views.py, write a simple view function, and return a string of Hello world!:
from django.http import HttpResponse
def index(request):
return HttpResponse('Hello World!')
Above thisindex
Function can be said to be the simplest view function. In fact, most of the applied views are much more complex than this. Django supports bothFunction based view(FBV, function based view) andClass based view(CBV, class based view), this is obviously FBV, receiving arequest
The request object as a parameter returned aHttpResponse
Object.
Route views
Next, we need to enable the routing system to access the view function just written. Therefore, first implement the routing table of sub application news, and create the file news / urls.py as follows:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
In every Django routing table module (URLs. Py), it is agreed that there must be oneurlpatterns
The list is used to store the route map table. Each element in the list is adjango.urls.path
The function encapsulates the route map, usually receiving the following three parameters:
-
route
: required, that is, the actual access route, the empty string is equal to/
, i.e. empty route -
view
: required, the view that the route will access -
name
: optional. The name of the route is convenient for subsequent use in the template
We will connect the news routing table just written to the global routing table. Because we hope that the news can be displayed on the homepage (i.e. through/
Can be accessed without/news
), so the URL of news application routing in global routing is an empty string. In django_news / urls.py, modify as follows:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('news.urls')),
]
Use heredjango.urls.include
Function to access the routing table of news application, andinclude
The parameter of the function is the string of the route module pathnews.urls
, manual operation is omittedimport
The trouble.
be careful
Order is very important when adding routing rules, because when trying to match, the order will be from top to bottom, so the most fuzzy route (i.e. empty route) should be placed at the bottom.
If your development server is still running (if it can’t be opened again), visit localhost: 8000, and you can see the familiar string of characters:
Understanding template: implementation of web front end
In the previous step, we learned how to implement the view and connect it to the routing configuration so that it can be accessed by users. Next, we will implement a Django template as the front-end of the web page, so as to present richer content to users.
Tips
If you have experience in developing other templates (or similar technologies), such as Jinja, EJS, JSP, etc., you will feel familiar with Django templates. If you don’t know what a template engine is, don’t worry. A simple understanding is one that can fill in content or even add code logicHTML like documentIt will eventually be converted into HTML documents that can be recognized by the browser.
Django template language foundation
Django template is essentially an HTML document, but only through some special syntax to achieve data filling. Here we will explain the three most commonly used Grammars:
Expression interpolation
The most commonly used grammar, no one. Through a pair of curly braces{{}}
Put in an expression, you can pass in the content of variables in the expression in the view, and finally render it into HTML code containing the specific content of variables. It should be noted that the supported expressions only support the following forms (which can be freely combined):
<! -- single variable -- >
{{ variable }}
<! -- get key of dictionary or property of object -- >
{{ dict.key }}
{{ object.attribute }}
<! -- get an element in the list -- >
{{ list.0 }}
For example, the template says:
<h1>{{ name }}</h1>
<p>{{ news.title }}</p>
<p>{{ news.visitors.0 }}</p>
If we pass in the following context dictionary in the view:
{
'name': 'Tuture',
'news': {
'title': 'Hello World',
'visitors': ['Tom', 'Marc'],
}
}
Then the final rendered HTML code is:
<h1>Tuture</h1>
<p>Hello World</p>
<p>Tom</p>
Conditional statement
The definition of a conditional statement is as follows:
{% if is_true %}
<h1>It is true!</h1>
{% else %}
<h1>It is false!</h1>
{% endif %}
If variableis_true
If it’s true, the final rendering is<h1>It is true!</h1>
, otherwise<h1>It is false!</h1>
。 Note: entire conditional statementmustwith{% endif %}
End, and{% else %}
yesOptionalOf.
Loop statement
The loop statement is used to display any long list content on the template. Its syntax is as follows:
{% for elem in some_list %}
<p>{{ elem }}</p>
{% endfor %}
If the incomingsome_list
by['Apple', 'Banana', 'Orange']
, the rendered HTML code is:
<p>Apple</p>
<p>Banana</p>
<p>Orange</p>
Implement the first Django template
It’s time to start, let’s implement the first Django template. Create a templates directory in the news directory, then a news directory in the templates directory, and create the index.html file in the news directory of the inner layer:
mkdir -p news/templates/news
touch news/templates/news/index.html
reflection
Sounds like a hassle, just create
news/templates
, and then put the template in it. Why create another news directory? This is because the template lookup mechanism of Django will collect all the templates in all applications. If the names of two templates conflict, one of them will not be accessed correctly. If you put it in the news subfolder, you can use thenews/index.html
Access, viaNamespaceThe mechanism avoids conflict.
The code of the template is as follows:
{% if news_list %}
<ul>
{% for elem in news_list %}
<li>
<h3>{{ elem.title }}</h3>
<p>{{ elem.content }}</p>
</li>
{% endfor %}
</ul>
{% else %}
<p>No news yet</p>
{% endif %}
These short lines of template code cover the three template syntax we just talked about: expression interpolation, condition statement and loop statement. If you forget the meaning of one of them, turn it up and have a look!
After the template is written, we will render it in the view. Open news/ views.py Document, the modification code is as follows:
from django.shortcuts import render
def index(request):
context = {
'news_list': [
{
"Title": "a new version of Tuque writing tool has been launched",
"Content": "it's amazing to be able to write a good tutorial at will",
},
{
"Title": "Tuque community officially launched a series of quick start tutorials",
"Content": "the Kung Fu of a cup of tea makes you start quickly without any worries",
},
]
}
return render(request, 'news/index.html', context=context)
Here we calldjango.shortcuts.render
Function to render the template. This function usually takes three parameters (there are other parameters, but we don’t care here):
-
request
: request object, directly put the parameters of the viewrequest
Just bring it in -
template_name
: template name, here is what we just creatednews/index.html
-
context
: the context object of the incoming template must be a dictionary. Each key in the dictionary corresponds to the variable in the template. Here we get some fake data, pretending to get it from the database.
Revisit localhost:8000 , let’s see if there is any content on our homepage:
Perfect!
Understanding model: linkage with database
Django’s MTV, we have talked about t (template) and V (view), and now we come to the final stage: m (model). Data model is the biggest difficulty for Django to get started. It takes a little effort to digest the content of this step, but trust me, when you pass the final stage of M, you can really start Django development! Let’s first introduce Django’s data model design.
Django’s design of data model can be regarded as a model, with some highlights:
- Due to the highly decoupled design, it is easy to switch various relational databases (SQLite by default, mysql, PostgreSQL, Oracle, etc.)
- The powerful ORM (object relation mapping) module makes it very easy to operate the database in Python and avoids the trouble of using SQL
- Excellent database migration mechanism, convenient to modify data schema, can adapt to the changing functional requirements
For beginners, we temporarily choose the default SQLite database, which saves the trouble of database configuration. In the later advanced tutorials, we will switch to other databases suitable for the production environment.
Understanding ORM
In short, ORM can convert the object-oriented code into the corresponding SQL statements, so as to operate the database. SQL is a standard computer language used to access and process database, but it is difficult to maintain directly in the code, and the requirements for users are also very high, and the poor SQL code query efficiency is very low. Therefore, using a well-designed ORM not only makes the code more readable, but also helps developers to optimize their queries and save a lot of effort.
Let’s look at some simple Django ORM examples:
#Query all models
#Equivalent to select * from blog
Blog.objects.all()
#Query a single model
#Equivalent to select * from blog WHERE ID=1
Blog.objects.get(id=1)
#Add a single model
#Equivalent to insert into blog (title, content) values ('Hello ',' world ')
blog = Blog(title='hello', content='world')
blog.save()
Is it much easier to operate than SQL?
Understand database migration
Database migration refers to transforming the model defined by Django into SQL code (i.e. migration file), and building tables (or updating tables) in the database. Look at the picture below:
The general development process is as follows:
- A new data model is defined by Django
- use
makemigrations
Command to create a migration file (stored in the migrations directory of the sub application) - use
migrate
Command execution migration - During the development, the model defined in step 1 is found to be incomplete, and the data model is updated
- Go to step 2 and repeat
Implement the first data model
Finally, it’s time to start. Let’s first define the data modelPost
, including titletitle
Fields andcontent
Field, the code is as follows:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
def __str__(self):
return self.title
Once defined, run the following command to create the migration file:
python manage.py makemigrations
You can see the output as follows:
Migrations for 'news':
news/migrations/0001_initial.py
- Create model Post
And successfully created news / migrations / 0001 automatically_ initial.py Migration scripts. Then we perform database migration:
python manage.py migrate
The output is as follows:
After the database migration, we can create a super user to log in to the background management:
python manage.py createsuperuser
Follow the prompts to fill in the user name and password. Then visit localhost: 8000 / admin to enter the background system login page:
Fill in the user name and password just set to enter the background management page:
Eh, where are the news applications we just created and the post model?
Configure background management interface
That’s because we didn’t implement the background management interface of news application. Fill in the code in news / admin.py as follows:
from django.contrib import admin
from .models import Post
admin.site.register(Post)
After entering the background management system again, you can see our news application and post model:
Click the + add button in the posts column to start adding news (content at will):
Add two or three news about it. You can also further explore the background management system, including modifying news, adding users and so on.
Add data query in view
Finally, we add the code to the view to query from the database:
from django.shortcuts import render
from .models import Post
def index(request):
context = { 'news_list': Post.objects.all() }
return render(request, 'news/index.html', context=context)
Visit the homepage of the website, you can see the news just added in the background management system:
be accomplished! In this tutorial, we completed a news release website, and can add news from the background management system, and finally show it to our website home page.
I hope this tutorial can give you a basic understanding of some of Django’s most important concepts and operations. Django also has many advanced games, such as advanced query in data model, field index, database replacement, etc., inheritance mechanism in template, internal label, etc., and how to handle all kinds of requests (post, put, etc.) in view. We will explain them one by one in the following more tutorials, which will not be separated!
Want to learn more wonderful practical technical courses? Come to Tuque community.