Vscode builds Django environment three: django comes with background management system, template rendering and uses mysql database

1. Django's own background management system

1.1. Create table

Open myappit models.pyand 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

insert image description here

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

insert image description here

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

insert image description here

Enter the newly created account and password to log in

insert image description here

This is the table just created, click on 添加us to add a set of data.

insert image description here
insert image description here

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 myapptheviews.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})

templatesThe directory needs to be modified as follows, the syntax of the rendering template used index.htmlhere .djangojanja2

<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

insert image description here

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.htmlAdd 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

insert image description here

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

insert image description here

Right-click the sqlite database and create a new query

insert image description here

Enter the query content, use .helpview help, .databasesview database, use .tablesview table, right click and select run query to see the result

select * from myapp_article

insert image description here

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 mysqlwe need to install apymysql

pip3 install pymysql

After installation, open mysitethe directory _init_.pyand 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

insert image description here

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 :

insert image description here

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.

Guess you like

Origin blog.csdn.net/weixin_43883625/article/details/129791875