1. Django's own background management system
1.1. Create table
Open myapp
it models.py
and add the following
from django.db import models
# Create your models here.
class Article(models.Model):
title = models.CharField('标题', max_length=256)
content = models.TextField('内容')
time = models.DateTimeField()
Next, you need to synchronize the database, which only requires two lines of commands.
python .\manage.py makemigrations
python .\manage.py migrate
At this time, you will find that there is an additional db.sqlite3 file in the root directory, and the opening is garbled. Yes, this is the newly created table. Stored in the root directory as text. One more step is needed, open admin.py in the myapp directory, add the following content, and use the background management system to manage the newly created table.
from django.contrib import admin
from myapp.models import Article
# Register your models here.
class ArticleAdmin(admin.ModelAdmin):
list_display = ['title', 'content', 'time']
admin.site.register(Article, ArticleAdmin)
2. Background management system
Django's background management system is already very complete. All we need to do is to create an account, log in, operate, nothing else, and we don't need to write anything ourselves.
Create an account
python manage.py createsuperuser
The weak password is prompted above, and you can set it according to your needs
The url of admin already exists by default, you can directly run the project here to access the Django background
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index')
]
python .\manage.py runserver
Enter in the browser address barhttp://127.0.0.1:8000/admin
Enter the newly created account and password to log in
This is the table just created, click on 添加
us to add a set of data.
3. Template rendering
3.1 Render data directly to the page
Once the data is available, it must be displayed on the front end, which requires template rendering. First, you need to return the data together when rendering the template, and open myapp
theviews.py
from django.shortcuts import render
from myapp.models import Article
# Create your views here.
def index(request):
article_list = Article.objects.all()
return render(request, 'index.html', {
'article_list': article_list})
templates
The directory needs to be modified as follows, the syntax of the rendering template used index.html
here .django
janja2
<html>
<head>
<title>test</title>
</head>
<body>
{
% for article in article_list %}
<h1>{
{
article.title }}</h1>
<span>{
{
article.time }}</span>
<p>{
{
article.content }}</p>
{
% endfor %}
</body>
</html>
refresh browser
3.2 Pass data to js
Sometimes the data needs to be processed and then rendered to the page. This requires the data to be sent to js first. The specific operation method is actually similar to that of direct rendering.
index.html
Add this code in
<script>
let articleList = {
{
article_list | safe }};
console.log(articleList)
</script>
Modify the code of views
from django.shortcuts import render
from myapp.models import Article
import json
from django.core import serializers
from django.core.serializers.json import DjangoJSONEncoder
# Create your views here.
def index(request):
article_list = serializers.serialize('python', Article.objects.all())
return render(request, 'index.html', {
'article_list': json.dumps(article_list, cls=DjangoJSONEncoder)})
refresh browser
4. Database
4.1. View the current database
Django comes with a sqlite database. If you don’t want to use it, you can replace it with mysql, mongodb or others you want to use. Here, take mysql as an example. Let's start by looking at our database structure.
Install the sqlite plugin in vscode
Right-click the sqlite database and create a new query
Enter the query content, use .help
view help, .databases
view database, use .tables
view table, right click and select run query to see the result
select * from myapp_article
4.2. Switch mysql database
Create a new django_test database
mysql> create database django_test;
Query OK, 1 row affected (0.01 sec)
mysql> show databases;
Switch to the newly created database, which is empty and has no tables
mysql> use django_test;
Database changed
mysql> show tables;
Empty set (0.00 sec)
For Django to use mysql
we need to install apymysql
pip3 install pymysql
After installation, open mysite
the directory _init_.py
and add two lines of code
# sqlite3
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_test',
'USER': 'root',
'PASSWORD': '你的密码',
'HOST': '你的主机名',
'PORT': '3306',
# 'NAME': BASE_DIR / 'db.sqlite3',
}
}
sync database
python manage.py makemigrations
python manage.py migrate
Then start the service, refresh 127.0.0.1:8000 and find that the data is gone, and you can’t log in with the previous account password when you open the background management, indicating that you have switched to mysql, the tables are empty, and there is no data. Let’s look at the newly created django_test below :
Just like we looked at the sqlite table before, we repeated the operations related to the background management before, and found that there is no difference, and the data can be operated, and the switch is completed.