2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Like + Follow + Collect = Learned
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.
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
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.
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.
- Password:
- 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.
- This password is too common.
- This password is entirely numeric.
- Bypass password validation and create user anyway? [y/N]: y
- 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.
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
from django.contrib import admin from account.models import User
class UserAdmin(admin.ModelAdmin): # Content to be displayed list_display = ['username', 'email']
admin.site.register(User, UserAdmin) ```
Here we need to import admin
andUser
Because 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.
Click "User Table" to see the information of this table in the database.
You can click the "Add" button to add new data to this table.
You can also modify or delete the specified data.
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
from django.contrib import admin from blog.models import Article
class ArticleAdmin(admin.ModelAdmin): # Content to be displayed list_display = ['id', 'title']
admin.site.register(Article, ArticleAdmin) ```
Let’s create an article and see.
Click the Add button next to "Article Information Tables" and fill in the following content.
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.
If you are not clear about the content of the entire project, you can look back at what I organized.Django Column。
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.
Open the project settings.py
File, findLANGUAGE_CODE
, set its value to'zh-hans'
. Then find TIME_ZONE
Set it toAsia/Shanghai
。
```python
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai' ```
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.
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
from django.apps import AppConfig
class AccountConfig(AppConfig): defaultautofield = 'django.db.models.BigAutoField' name = 'account' verbose_name = 'User Management' ```
blog
The same applies.
```python
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.
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
from django.db import models
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)
- class Meta:
- # 自定义表名
- db_table = 'user'
- # 表别名
- verbose_name = '用户表'
- verbose_name_plural = '用户表'
```
Refresh the page and you will see that the "s" after "User Table" is gone.
blog
Same reason.
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.
We should display the username.
Let's modify it here first blog
The fields to display.
```python
from django.contrib import admin from blog.models import Article
def get_author(obj): return obj.user.username
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'
admin.site.register(Article, ArticleAdmin) ```
Use the get_author method to associate the foreign key username
The fields are displayed.
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
from django.db import models
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)
- class Meta:
- # 自定义表名
- db_table = 'user'
- # 表别名
- verbose_name = '用户表'
- verbose_name_plural = '用户表'
-
- # 返回用户名
- def __str__(self):
- 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.
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.
```python
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.
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
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.
That's all for this article. In the next article, I will introduce how to load information from the database on the front page.
Like + Follow + Collect = Learned