Technology Sharing

Django's own backend

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina


theme: smartblue

Introduction

Like + Follow + Collect = Learned

00.png

The previous article talked about Django operateMySQL The method explains how to create a model and how to add, delete, modify and query the database. However, it is a bit troublesome to write code every time you modify the data.

Is there a simpler way?

Yes, yes.Django In fact, it comes with a backend with a graphical interface, on which you can easily operate various data contents.

Next, let’s talk about how to use this built-in background.

Configure the background routing address

In fact, creating Django The backend routing address has been configured for us when the project was started.

If you follow my previous article step by step, the background routing may be deleted. It doesn't matter, just add it back.

Open the project urls.py File, findurlpatterns This variable fills in the background routing.

```python

urls.py project routing file

from django.urls import path from blog.views import blogIndex

urlpatterns = [ #Other routes are omitted#The following sentence is the configuration background route path ('admin/', admin.site.urls) ] ```

After the configuration is complete, start the project and open it in the browser http://127.0.0.1:8000/admin/ You can see the backend login page.

01.png

Create an administrator account

If there is a login page, you need a corresponding account to log in.

So we need to create a super account first.

Open the terminal, enter the project directory, and enter the following command to create a super administrator account.

python manage.py createsuperuser

Then the terminal will return this line of information to you, asking you to enter the username (account) of the super administrator

Username (leave blank to use 'xxx'): admin

Here 'xxx' is my computer name, you can enter the super administrator account after the colon. Here I enter admin

After entering your username, it will ask you to enter your email address.

Email address: 123@qq.com

After entering your email address, you will be asked to enter your password twice.

  1. Password:
  2. Password (again):

The password I entered here is 12345678, it smartly reminded me that my password was too common, but I entered y and stuck with such a simple password.

  1. This password is too common.
  2. This password is entirely numeric.
  3. Bypass password validation and create user anyway? [y/N]: y
  4. Superuser created successfully.

See Superuser created successfully. This sentence means that the account has been created successfully.

Now open in the browser http://127.0.0.1:8000/admin/, account number input admin, password input 12345678 You can log in successfully.

02.png

Model association background

We have previously used code to operate the database, which is not very convenient.

Django It provides a way for us to bind the application model to the background, so that we can directly operate the data in the background interface.

The above article created account Application as an example.

exist account Found in the appadmin.py File, write the following code.

```python

account/admin.py

from django.contrib import admin from account.models import User

class UserAdmin(admin.ModelAdmin): # Content to be displayed list_display = ['username', 'email']

Bind the User model to the UserAdmin

admin.site.register(User, UserAdmin) ```

Here we need to import admin andUserBecause we want to account The application model is associated with the backend.

Create a file called UserAdmin The class, written in itlist_display = ['username', 'email'] , which means to display it on the background pageusername andemail These two fields.

at last admin.site.register(User, UserAdmin) means thatUser The model and the backend are bound together.

Run the project and open http://127.0.0.1:8000/admin/ And log in, you can see the model you just bound.

03.png

Click "User Table" to see the information of this table in the database.

04.png

You can click the "Add" button to add new data to this table.

05.png

You can also modify or delete the specified data.

06.png

The data modified on the background page will directly affect the data in the database.

In the same way, blog The application model is associated with the backend. The operation here is the same as before, so I will not repeat it.

```python

blog/admin.py

from django.contrib import admin from blog.models import Article

Register your models here.

class ArticleAdmin(admin.ModelAdmin): # Content to be displayed list_display = ['id', 'title']

Bind the User model to the UserAdmin

admin.site.register(Article, ArticleAdmin) ```

07.png

Let’s create an article and see.

Click the Add button next to "Article Information Tables" and fill in the following content.

08.png

Click SAVE After clicking the button, the data will be written into the database. Return to the list page of "Article Information Tables" to see the data just written.

09.png

If you are not clear about the content of the entire project, you can look back at what I organized.Django Column

Basic configuration of the background

In the previous operation, careful workers may have noticed some problems, such as why the interface is in English? Why is there an "s" after the table name? Why is the User field optional when creating an article not the username, but User object(1)

Next we will solve these problems one by one.

Set time zone and language

Open the project settings.py File, findLANGUAGE_CODE , set its value to'zh-hans'. Then find TIME_ZONE Set it toAsia/Shanghai

```python

settings.py

language

LANGUAGE_CODE = 'zh-hans'

Time zone

TIME_ZONE = 'Asia/Shanghai' ```

10.png

Change the column name to Chinese

But at this time ACCOUNT andBLOG Still in English, hereDjango It cannot be translated directly into Chinese, you need to configure aliases for these two applications.

11.png

The configuration place is in each application's own apps.py In the file, throughverbose_name Variables come from custom column names.

by account Application as an example.

```python

account/apps.py

from django.apps import AppConfig

class AccountConfig(AppConfig): defaultautofield = 'django.db.models.BigAutoField' name = 'account' verbose_name = 'User Management' ```

blog The same applies.

```python

blog/apps.py

from django.apps import AppConfig

class BlogConfig(AppConfig): defaultautofield = 'django.db.models.BigAutoField' name = 'blog' verbose_name = 'Article Management' ```

At this time, refresh the page and you can see that the column name has been changed.

12.png

Remove plural form

The "s" after the table name is Django It comes with it. To delete this "s", you also need to configure the alias of the table.

In the model files of each application (models.py) Meta informationalverbose_name_plural

by account Application as an example.

```python

account/models.py

from django.db import models

Create a user table

class User(models.Model): id = models.AutoField(primarykey=True) # Username username = models.CharField('username', maxlength=30, null=True, blank=True, unique=True) # Password password = models.CharField('password', max_length=30) # Email = models.EmailField('email', unique=True, null=True, blank=True)

  1. class Meta:
  2. # 自定义表名
  3. db_table = 'user'
  4. # 表别名
  5. verbose_name = '用户表'
  6. verbose_name_plural = '用户表'

```

Refresh the page and you will see that the "s" after "User Table" is gone.

13.png

blog Same reason.

Show foreign key fields

When we add an article, we need to enter and select the author of the article. The author of the article table is associated with the user table.

When adding an author, the page directly displays the name "User object". If there are too many users, we will not be able to distinguish who is who.

14.png

We should display the username.

Let's modify it here first blog The fields to display.

```python

blog/admin.py

from django.contrib import admin from blog.models import Article

Get Author

This obj object is used to receive the Article instance

def get_author(obj): return obj.user.username

Register your models here.

class ArticleAdmin(admin.ModelAdmin): # Content to be displayed # At this point, you can use getauthor is replaced by the username. No single quotes or parentheses are needed here. # Django is using listWhen display is called, a parameter is passed to the method by default. listdisplay = ['id', getauthor, 'title', 'content']

getauthor.shortdescription = 'Author'

Bind the User model to the UserAdmin

admin.site.register(Article, ArticleAdmin) ```

Use the get_author method to associate the foreign key username The fields are displayed.

15.png

Now we can see who is the author of this article. But we still need to display the username on the edit page.

Modification is required at this time User Models will do.

```python

account/models.py

from django.db import models

Create a user table

class User(models.Model): id = models.AutoField(primarykey=True) # Username username = models.CharField('username', maxlength=30, null=True, blank=True, unique=True) # Password password = models.CharField('password', max_length=30) # Email = models.EmailField('email', unique=True, null=True, blank=True)

  1. class Meta:
  2. # 自定义表名
  3. db_table = 'user'
  4. # 表别名
  5. verbose_name = '用户表'
  6. verbose_name_plural = '用户表'
  7. # 返回用户名
  8. def __str__(self):
  9. return self.username

```

exist account/models.py Finally add__str__ Method, returnsusername

At this time, you can see the user name in the edit page of the article information.

16.png

Custom edited jump links

In the article management page, if you want to edit an article, you can only click the "ID" field to jump to the edit page. If you want to jump to the edit page by clicking other fields, you need to configure it manually. blog/admin.py For example, I can click "TITLE" to jump to the editing page.

17.png

```python

blog/admin.py

Omit some code

class ArticleAdmin(admin.ModelAdmin): # List of contents to be displayeddisplay = ['id', getauthor, 'title', 'content'] # List of fields that can be jumpeddisplaylinks = ['id', 'title'] # Omit some code```

I am here ArticleAdmin Addedlist_display_links = ['id', 'title'], indicating click id andtitle You can jump to the edit page.

Read-only properties

When editing content, we don't want certain fields to be editable. For example, the blog ID cannot be edited.

allowable blog/admin.py Addreadonly_fields Specifies that the field cannot be modified.

```python

blog/admin.py

Omit some code

class ArticleAdmin(admin.ModelAdmin): # Read-only attribute readonly_fields = ['id'] # Omit some code```

When editing at this time, the value of the id field cannot be modified.

18.png


That's all for this article. In the next article, I will introduce how to load information from the database on the front page.

IMG_8982.GIF

Like + Follow + Collect = Learned