For Django beginners, the most confusing thing is how to implement their own code step by step in a complex project directory (such as when to add a URL and when to register an APP). This article uses a hello world as an example to help You sort out the steps to implement a Django project.
Table of contents
0. Project implementation mind map
1. Django installation, creating Django project and APP
Django
To install, just use pip install
or conda install
:
# pip
pip install django
# conda
conda install django
Personally recommend using Anaconda
Create a virtual environment for installation. For specific reasons and Anaconda
installation steps, please refer to my blog " Teach you step by step Anaconda installation and configuration and pycharm selection of Anaconda environment "
As for the creation of Django projects and APPs, you can refer to my blog " Django Study Notes (3) - Creating Django Projects and APPs Using the Command Line "
2. Database configuration
After you have completed the above three steps, created a hello_world
Django project named and registered an hello
APP named , you can start our topic today.
When your project requires a database (take as mysql
an example , because I only know it mysql
), you need to perform the following two steps.
2.1 Install third-party database modules
Although Django
it is easier to operate the database, it requires third-party module support. Same as previous installation, you can use pip
install or conda
install.
# pip
pip install mysqlclient
# conda
conda install mysqlclient
2.2 Create a new database
Django
The database cannot be automatically generated, so we need to create a database ourselves. For example, use directly Navicat
to create a new database.
2.3 Database configuration
After creating the database corresponding to the project, find settings.py
the file. For example, the directory of my file is in 'hello_world > hello_world', and then find the following fields:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
Replace it with:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 数据库引擎
'NAME': 'hello_world', # 数据库名字
'USER': 'xxx',
'PASSWORD': 'xxx',
'HOST': '127.0.0.1', # 服务器主机, 本地就在 127.0.0.1 或者 localhost
'PORT': 3306,
}
}
The above 'xxx'
represents your field, USER
the login name of your database, PASSWORD
and the password of your database. NAME
is the name of your database, our database name is called hello_world
.
3. Writing models files
If you need to use a database, then you need to write the fields in the database. After you configure the fields settings.py
in DATABASES
, find the file in APP models.py
, which is 'hello_world > hello' in our project. Each class in this file is a table in the database. As follows:
from django.db import models
class User(models.Model):
"""
用户表
"""
username = models.CharField(verbose_name='用户名', max_length=32)
password = models.CharField(verbose_name='密码', max_length=64)
Then we enter the following two lines of code in the terminal:
python manage.py makemigrations
python manage.py migrate
A table named is generated in our database hello_user
(the naming rule is APP 名字_类名
(lowercase)). The fields in the table are the fields in the class, but an auto-incrementing primary key will be automatically generated id
.
4. Write urls
This is the most easily forgotten step when I first started learning django.
Every time we write a new backend logic, we need to urls.py
write the path clearly in the file. The files are in 'hello_world > hello_world'.
There is a default list in the file:
urlpatterns = [
path('admin/', admin.site.urls),
]
When the service starts, you can directly enter localhost:8080/admin/
to view the page (the port number I set is 8080). And when we want to create our own backend logic, we need to import the file in this file first views.py
.
from hello import views
Of course, considering that if there is enough back-end logic (such as user management, financial management, etc.), views.py
the file will be very long. In order to simplify the later code maintenance, you can views.py
delete the file directly, and then hello
create a folder under the folder views
. Create different files in this folder according to different functions (for example, for user management user.py
, for financial management financial.py
), and then urls.py
import the package in the file like this:
from hello.views import user, financial
But since our project is very simple, views.py
we can just write it in the file here. Suppose we want a method called print_hello_world
, then urlpatterns
change to:
urlpatterns = [
path('admin/', admin.site.urls),
path('hello_world/', views.print_hello_wolrd),
]
After adding this sentence, every time we visit localhost:8080/hello_world/
the page, the method views.py
in the file will be automatically executed print_hello_world
.
Note:
- Since
urlpatterns
is a list, be sure to add commas! - There is no need to add the path here
/
, that is/hello_world/
, if you become/hello_world/
, accessinglocalhost:8080/hello_world/
the page will result in 404. If you want to access your page, you must access itlocalhost:8080//hello_world/
(with an extra slash).
5 Write views files and html pages
Since views
and html
are used in combination, they are explained together. The first thing to note is that any views.py
method inside must have a return value at the end, otherwise a 500 error will be reported. This return value must be one of the following three: render
, redirect
, or HttpResponse
.
from django.shortcuts import render, redirect, HttpResponse
I haven't looked at these three methods too carefully, but in simple terms, render
it is to render the page and pass parameters to the page. redirect
It is a redirection, jumping to other urls
paths in , you can also pass parameters, but the parameters have to be spliced into url
. HttpResponse
It is to directly output a text on the page, and I personally often use it for testing.
Note: render
The parameter in is the page (for example hello.html
), and redirect
the parameter in is urls
the path in (for example hello_world/
)
Taking a simple example as an example, we only need to jump to hello.html
the page named , which only has hello world
the parameters passed, views.py
as follows:
def print_hello_world(request):
return render(request, 'hello.html')
hello.html
Just one line:
<span>hello world</span>
Consider the parameter-passing version again. In render
passing parameters, you need to pass a dictionary, views.py
as follows:
def print_hello_world(request):
context = {
'msg': 'hello world'
}
return render(request, 'hello.html', context)
And hello.html
in should become:
<span>{
{ msg }}</span>
That is, a double curly bracket {
{}}
followed by the key name in the passed dictionary (based on the memory of vue I learned 4 years ago, it seems to be the same as vue?).
Of course, django also supports html
the use of for
statements and if
statements in . views.py
middle:
def print_hello_world(request):
context = {
'msg': ['hello', 'world'],
'is_show': True,
}
return render(request, 'hello.html', context)
hello.html
middle:
{% if is_show == True %}
{% for item in msg %}
<span>{
{ item }} </span>
{% endfor %}
{% endif %}
Note:
for
Statements andif
statements use{%%}
this symbol, and remember to follow{% endfor %}
and at the end{% endif %}
, whileif
statements also supportelif
andelse
.- If you want to use square brackets such as index
[]
to get the value, then use the method, as follows.0
:.1
<span>{
{ msg.0 }} </span>
<span>{
{ msg.1 }}</span>
6. Summary
The above is how to implement a simple Django project from scratch. Of course, the things involved in this article are very simple, just a streamlined logical thinking process. There are also many skills and technologies not mentioned in this article, such as forms, form
but I believe Baidu can solve 99% of these problems.