Django series: Creation and configuration of Django applications (apps)

Django series
Creation and configuration of Django applications (apps)

Author : Li Juncai (jcLee95) : https://blog.csdn.net/qq_28550263
Email: [email protected]
Article address : https://blog.csdn.net/qq_28550263/article/details/132893616


【介绍】:应用是Django项目的组成部分,一个Django项目可以分为多个应用,本文讲解Django应用(app)的创建,并实际完成一个简单应用的配置和开发。

Previous section: " Django's project structure and configuration analysis " | Next section: " Advanced Django routing rules "


1 Overview

A Django application (App) is a modular component of a Django project that implements specific functionality. A Django project usually consists of multiple applications, each with its own functionality and responsibilities. In the previous article, we introduced the difference between applications and projects in Django, and how to create them using command line tools. Next, this article will comprehensively introduce the related usage of applications (apps) in Django, and create and complete an application (app) based on a Django project.

2. Create your first Django app

After you have created the root directory of a Django project and entered the directory, you can follow the following steps to create a Django application, configure it, write simple code, and finally run it.

2.1 Create a Django application

In the Django project root directory (myproject in this case), run the following command to create a Django application:

python manage.py startapp myapp

This will create an myappapplication directory called , which contains the basic structure of a Django application.

Insert image description here

2.2 Register Django application

Open the file located in the root directory of the project myproject/settings.pyand locate INSTALLED_APPSSettings. Add your application to this list:

INSTALLED_APPS = [
    # ...
    'myapp',  # 添加该项以注册应用,应用名即使用 startapp 指定的名称
]

This will tell the Django framework that your application exists in the current project.

2.3 Writing data models (Models)

Define your model in a file under myappthe directory . models.pyHere is an example:

from django.db import models

# 创建一个名为 MyModel 的 Django 数据模型类
class MyModel(models.Model):
    # 定义一个名为 name 的字段,类型为 CharField,最大长度为 100 个字符
    name = models.CharField(max_length=100)
    
    # 定义一个名为 description 的字段,类型为 TextField,用于存储文本数据
    description = models.TextField()

    # 定义一个特殊方法 __str__,用于返回对象的字符串表示,通常在管理界面中显示对象时使用
    def __str__(self):
        # 返回对象的 name 属性作为字符串表示
        return self.name

2.4 Create views (Views)

Create the view function in a file in myappthe directory . views.pyHere's a simple example:

from django.http import JsonResponse
from .models import MyModel

# 导入 Django 的 render 函数,用于渲染 HTML 模板
from django.shortcuts import render

def my_view(request):
    # 查询 MyModel 中的所有对象
    my_objects = MyModel.objects.all()

    # 创建一个包含所有对象信息的列表
    data = []
    for obj in my_objects:
        data.append({
    
    
            'name': obj.name,
            'description': obj.description,
        })

    # 返回 JSON 响应
    return JsonResponse(data, safe=False)

2.5 Assign URL to app

Django's routing is hierarchical. You can assign a route to the app first, that is, use incluedea function to include a file under a specified application as the routing file of the sub-application. However, this is not necessary. In theory, if the project is simple enough, the root routing file of the project (urls.py file in the project home directory) can be used directly without creating an app for the entire project. The project home directory refers to the project root. Directory with the same name as the project) directly assigns views. It can be seen that this is actually completing the work of the Controller (scheduler) in the MVC framework.

In a file in the project root directory myproject/urls.py, include the URL of your application into the project:

from django.contrib import admin

# 导入 Django 的 URL 路由和包含模块
from django.urls import path, include

# 定义 URL 映射关系列表 urlpatterns
urlpatterns = [
    # 当用户访问 /admin/ 路径时,将请求交给 admin.site.urls 处理
    path('admin/', admin.site.urls),
    
    # 添加这行:当用户访问 /myapp/ 路径时,将请求交给 myapp.urls 模块中定义的 URL 处理
    path('myapp/', include('myapp.urls')),
]

The request path('myapp/', include('myapp.urls'))is mapped to an application named myapp, and the application's URL mapping is defined in the myapp.urls(urls.py under myapp application) module.
This way, once the user accesses /myapp/the route, myapp.urlsthe request will be handled using URL handling in the module, which allows the application to define its own views and functions and associate them with the main project's URL mapping.

2.6 Assign URLs to views under the app

myappCreate a file named under the directory and urls.pyadd the following content:

from django.urls import path
from . import views

# 都将继承app路由 'myapp/'
urlpatterns = [
    # 为# views模块下的视图 my_view 分配路由 'myapp/myview/'
    path('myview/', views.my_view, name='my_view'),  
]

You can specify multiple route assignments in the urlpatterns list to views.pyassign routes to different view functions or view methods in .

2.7 Create database table (migrate)

Run the following command to create the database table:

python manage.py makemigrations # 创建数据库模型的迁移文件
python manage.py migrate # 应用数据库迁移

This will create a database table based on what is defined in the model.

Insert image description here
By default, you do not need to install any other database, a SQLite database file will be automatically generated. SQLite database is a lightweight database commonly used for mobile devices and application embedding. By default, it will be saved in the root directory of the project after being generated:

Insert image description here

Here I use SQLiteSpy software to open it:

Insert image description here
You can see the table corresponding to the current app: myapp_mymodel. Among them myappis the current application name, mymodelwhich corresponds to the current data model and is expressed in lowercase. It is separated from the application by an underscore. If you define multiple data model classes in a Django application (app), but after performing migration, corresponding data tables with similar names will also be generated.

It should be noted that if your data model is not used, the data migration file will not be generated during data migration, and subsequent application data migration will not occur accordingly. For example, if the view function is changed to:

from django.http import HttpResponse
def my_view(request):
   return HttpResponse("Hello, Django!")

This does not use the data model at all. It can also work, but it will not perform data migration and the related tables will not be created in the corresponding database.

Not only Django, many similar frameworks provide similar commands or programming interfaces when executing. in:

1. makemigrations command

The makemigrations command is used to create migration files for database models. Migration files contain instructions on how to change the database model.

If Django does not detect any changes to the database models (Models), you will see "No changes detected" after executing the command to create a migration file:

No changes detected

2. migrate command

The migrate command is used to apply database migrations to synchronize the database schema with the application's model .

When you run the migrate command, Django examines all migration files and uses the instructions in those files to create, modify, or delete database tables to be consistent with your model definition.

The migrate command executes migration files sequentially, starting with the oldest migration and applying changes incrementally to ensure that the database remains consistent with the current application state.

2.8 Access our applications in a browser

You can now run Django's development server to view the application:

python manage.py runserver

Visit http://localhost:8000/myapp/myview/to see "Hello, Django!" in your browser. This is the basic process for creating and running a simple Django application. This application can be extended and customized to suit your needs.

Insert image description here

Due to the use of JsonResponse , the latest browsers automatically provide the option of beautiful output of JSON. However, since we have no data here, what we see is a "[]".

We can manually add data in the admin later to see some effects, but here, we insert data in two ways, one is Django Shell, and the other is using SQL language. If you are using SQL language, you need a small software that can open the SQLite database (if you are using other databases, you can also use the corresponding software or Sell tool)/

Insert data using Django Shell

Since the table is created through the data model MyModel , we can insert data in the following steps:

  1. Run the following command in the project root directory to open the Django Shell:
python manage.py shell
  1. Import your model class MyModel:
from myapp.models import MyModel
  1. Create new data records and save them. You can use the model class's createmethod or directly instantiate the model class and call savethe method. Here is sample code:
# 使用 create 方法创建新记录
MyModel.objects.create(name="记录1", description="这是记录1的描述")
MyModel.objects.create(name="记录2", description="这是记录2的描述")

# 或者直接实例化模型类并保存
record3 = MyModel(name="记录3", description="这是记录3的描述")
record3.save()
  1. Exit Django Shell:
exit()

As shown in the picture:
Insert image description here

Now, you have manually inserted several pieces of data into MyModelthe table, as shown in the figure:

Insert image description here

You can add more data records as needed. This data will be persisted in the database and can be queried and used in your application.
Now, re-run the development server:

python manage.py runserver

Open the browser again and enter the page http://127.0.0.1:8000/myapp/myview/. You can see that the displayed result is no longer an empty array:

Insert image description here
Is it a bit unexpected and feels like the code is garbled? ——Actually not, it’s just that normal Chinese has been encoded.

This is when you access http://127.0.0.1:8000/myapp/myview/, your view function returns a response in JSON format. This is because it is used in the view function JsonResponseand returns a JSON data containing the model data. The display mode of JSON data is the default, which is rendered in Unicode encoding. This is why you see Unicode escape characters in your browser.

If you want to display JSON data in a more readable way in your browser, you can add a browser extension or use an online JSON viewer. These tools can format and display JSON data into a more readable form.

It should be pointed out that this method only applies to the insertion of initialization data or test data. In a real production environment, data is usually added dynamically through the user interface or other means.

Insert data directly using SQL

We can also directly enter SQL statements to insert data through database management tools, such as MySQL Workbench, pgAdmin (for PostgreSQL), SQLite's SQLiteSqy, etc. For example, the following is inserting data in SQLiteSqy:

Insert image description here
The most important sentences are:

INSERT INTO myapp_mymodel (name, description)
VALUES
  ('记录1', '这是记录1的描述'),
  ('记录2', '这是记录2的描述'),
  ('记录3', '这是记录3的描述');

3. Use templates in your app

Create a folder named templates in your app directory to store your HTML template files. my_template.htmlAs an example, here we create an HTML file named in the directory and edit its text content as follows:

<!-- my_template.html -->

<!DOCTYPE html>
<html>
<head>
    <title>我的模板</title>
</head>
<body>
    <h1>欢迎来到{
   
   { site_name }}网站</h1>
    <p>今天是{
   
   { current_date }}</p>
    
    <ul>
        {% for item in items %}
            <li>{
   
   { item }}</li>
        {% endfor %}
    </ul>
    
    <p>总价: ${
   
   { total_price|floatformat:2 }}</p>
</body>
</html>

In this example, we use the template syntax provided by Django. The double curly brackets represent the interpolation syntax, and the middle is the Python variable name, which represents the inserted value. Readers who have learned the front-end, in fact, many of them are the same, such as in the Vue framework . This interpolation is used. This interpolation method is called Mustache interpolation syntax . For example in this case:

  • { { site_name }}: This is the interpolation syntax used to insert the value of a variable in the template.
  • { { current_date }}: It is also an interpolation syntax, used to insert the value of the current date.

{ { total_price|floatformat:2 }}The filter syntax of Django templates is used. This example formats the variable total_price as a floating point number with two decimal places. One feature of the filter syntax is that |the following indicates the filtering conditions for the previous variables.

{% for item in items %}The loop statement that forms {% endfor %}a template is similar to the vue-for directive in the front-end framework Vue .

In this example:

<ul>
  {% for item in items %}
    <li>{
   
   { item }}</li>
  {% endfor %}
</ul>

This statement iterates over a list named items and inserts elements in the list on each iteration.

Next, we add a new view function in this app views.pyand use this HTML template in the view function to return the HTTP request:

# 新增到 views.py
from django.shortcuts import render

def my_template_view(request):
    site_name = "我的Django网站"
    current_date = "2023-09-15"
    items = ["物品1", "物品2", "物品3"]
    total_price = 123.45

    context = {
    
    
        'site_name': site_name,
        'current_date': current_date,
        'items': items,
        'total_price': total_price,
    }
    return render(request, 'my_template.html', context)

Among them, render is a view function in the Django framework, used to render HTML templates and generate HTTP responses. Its main function is to combine the template with data to generate the final HTML page, and then return the page to the client browser as an HTTP response.

Next, add the route of the view function my_template_view in the urlpatterns of the current app's urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('myview/', views.my_view, name='my_view'),
    # 新增
    path('my_template_view/', views.my_template_view, name='my_template_view'),
]

Next, we also need to change a Django project configuration. Open the project settings.pyand TEMPLATESadd it under the configuration item to allow Django to find the folders 'APP_DIRS': True,in each application (app) to obtain template files:templates

TEMPLATES = [
    {
    
    
        # ...
        'APP_DIRS': True,
    },
]

Insert image description here

APP_DIRSIndicates whether the Django engine should look for template source files in installed applications, so be sure to ensure that the INSTALLED_APPScurrent application has been installed (registered) in such as:
Insert image description here
In this way, when you run python manage.py runserver, access http://127.0.0.1:8000/myapp/my_template_view/will see the following effect:

Insert image description here

Otherwise, a template not found error may be displayed during access, such as:

Insert image description here
In addition, sometimes Django may cache template search results. A common debugging tip in development is that if you confirm that you have changed the correct code, but the new effect is never rendered, you can use the command to clear Django's cache clearcache:

python manage.py clearcache

4. Manage app in Django Admin

Django's admin is a powerful function that automatically generates a management backend interface. It allows developers to easily manage website data, including model data in the database.

4.1 Creation of super user

Before using Django's admin, you first need to create a super user account in order to log in to the admin background management interface and perform management operations. A superuser can be created using the following command:

python manage.py createsuperuser

Then, follow the prompts to enter your username, email address, and password to create a superuser account. For example:

Insert image description here
As a demonstration, I deliberately used a password that was too short. You can see that Django prompted this, saying:
This password is too short. It must contain at least 8 characters. This password is too short. It must contain at least 8 characters.
This password is too common. This password is too common.
This password is entirely numeric. This password is entirely numeric.
But nevertheless, we go through:
Bypass password validation and create user anyway?
Answer "Y" to confirm.

4.1 Register model

If there is no right

To manage model data in the admin background management interface, the model needs to be registered in admin.pya file. In your application's admin.py file, import the relevant models and admin.site.registerregister them using the function.

Note that if you do not register it in admin.py, you will not be able to see our model after logging in to the management interface below:
Insert image description here
Group (user group) and Users (user) in the picture are both models of Django’s own management application, and There is no model that we define.

# myapp 应用的 admin.py
from django.contrib import admin
from .models import MyModel

# Register your models here.
admin.site.register(MyModel)

4.3 Access the admin background

Access the admin background management interface in the browser, and run the development server (runserver command) under the URL, which is usually http://127.0.0.1/admin/. You can log in using the superuser account created earlier. For example, here we visit http://127.0.0.1:8000/admin:

Insert image description here

Since you have not logged in yet, Django's permission management will automatically redirect to the admin's login route, that is http://127.0.0.1:8000/admin/login/?next=/admin/. We only need to enter the previously created super user name and corresponding password here to enter the admin home page.

Insert image description here
You can see that the data model MyModels under the myapp application is displayed in Admin (as My Models).

4.4 Managing model data

Click on the data model (My Models) below in the myapp application to see:

Insert image description here
You can see previously added data

You can do the following:

  • View data : In the admin background, you can view model data in the database, presented in lists, details, or other forms.

  • Add data : You can add new data records, fill in the fields and save.

  • Edit and update data : Existing data records can be edited and changes saved.

  • Delete data : You can delete data records that are no longer needed.

4.5 Customize the admin interface

Django's admin interface can be customized to meet specific needs. You can define the admin class of the model in the admin.py file and customize field display, filter, search, sorting and other options to change the way the model is presented in the admin interface.

from django.contrib import admin
from .models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('name', 'description')

admin.site.register(MyModel, MyModelAdmin)

4.6 Extended functions

You can also use third-party libraries and plug-ins to extend the functionality of Django admin, such as django-import-export for importing and exporting data, or django-grappelli for beautifying the admin interface.

For example, you can install and use django-grappelli:

pip install django-grappelli

Then register it in INSTALLED_APPS in settings.py:

INSTALLED_APPS = (
    'grappelli',
    'django.contrib.admin',
    # ...
)

Then assign routes:

from django.conf.urls import include

urlpatterns = [
    path('grappelli/', include('grappelli.urls')), # grappelli URLS
    path('admin/', admin.site.urls),
]

Then register the template's context handler:

TEMPLATES = [
    {
    
    
        ...
        'OPTIONS': {
    
    
            'context_processors': [
                ...
                'django.template.context_processors.request',
                ...
            ],
        },
    },
]

When officially used for server deployment, you can use the following methods to collect media files:

python manage.py collectstatic

With the same function, the admin interface has been "beautified". For example, when you visit " http://127.0.0.1:8000/admin/myapp/mymodel/" again, you can see:
Insert image description here

Guess you like

Origin blog.csdn.net/qq_28550263/article/details/132893722