Django study notes (4) - a simple implementation process of a Django project

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.

0. Project implementation mind map

Project implementation process

1. Django installation, creating Django project and APP

DjangoTo install, just use pip installor conda install:

# pip
pip install django

# conda
conda install django

Personally recommend using AnacondaCreate a virtual environment for installation. For specific reasons and Anacondainstallation 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_worldDjango project named and registered an helloAPP named , you can start our topic today.

When your project requires a database (take as mysqlan example , because I only know it mysql), you need to perform the following two steps.

2.1 Install third-party database modules

Although Djangoit is easier to operate the database, it requires third-party module support. Same as previous installation, you can use pipinstall or condainstall.

# pip
pip install mysqlclient

# conda
conda install mysqlclient

2.2 Create a new database

DjangoThe database cannot be automatically generated, so we need to create a database ourselves. For example, use directly Navicatto create a new database.

2.3 Database configuration

After creating the database corresponding to the project, find settings.pythe 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, USERthe login name of your database, PASSWORDand the password of your database. NAMEis 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.pyin 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.pywrite 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.pythe file will be very long. In order to simplify the later code maintenance, you can views.pydelete the file directly, and then hellocreate 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.pyimport the package in the file like this:

from hello.views import user, financial

But since our project is very simple, views.pywe can just write it in the file here. Suppose we want a method called print_hello_world, then urlpatternschange 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.pyin the file will be automatically executed print_hello_world.

Note:

  1. Since urlpatternsis a list, be sure to add commas!
  2. There is no need to add the path here /, that is /hello_world/, if you become /hello_world/, accessing localhost:8080/hello_world/the page will result in 404. If you want to access your page, you must access it localhost:8080//hello_world/(with an extra slash).

5 Write views files and html pages

Since viewsand htmlare used in combination, they are explained together. The first thing to note is that any views.pymethod 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, renderit is to render the page and pass parameters to the page. redirectIt is a redirection, jumping to other urlspaths in , you can also pass parameters, but the parameters have to be spliced ​​into url. HttpResponseIt 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 redirectthe parameter in is urlsthe path in (for example hello_world/)

Taking a simple example as an example, we only need to jump to hello.htmlthe page named , which only has hello worldthe parameters passed, views.pyas follows:

def print_hello_world(request):
    return render(request, 'hello.html')

hello.htmlJust one line:

<span>hello world</span>

Consider the parameter-passing version again. In renderpassing parameters, you need to pass a dictionary, views.pyas follows:

def print_hello_world(request):
    context = {
    
    
        'msg': 'hello world'
    }
    return render(request, 'hello.html', context)

And hello.htmlin 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 htmlthe use of forstatements and ifstatements in . views.pymiddle:

def print_hello_world(request):
    context = {
    
    
        'msg': ['hello', 'world'],
        'is_show': True,
    }
    return render(request, 'hello.html', context)

hello.htmlmiddle:

{% if is_show == True %}
    {% for item in msg %}
        <span>{
   
   { item }} </span>
    {% endfor %}
{% endif %}

Note:

  1. forStatements and ifstatements use {%%}this symbol, and remember to follow {% endfor %}and at the end {% endif %}, while ifstatements also support elifand else.
  2. 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, formbut I believe Baidu can solve 99% of these problems.

Guess you like

Origin blog.csdn.net/qq_35357274/article/details/125976858