Use Django+MySQL to quickly build a website of your own

Use Django+MySQL to quickly build a website of your own

Hello, friends, how are you~~ It’s another day to get new skills every day. Today, let’s sort out how to install the openEuler operating system on VMware Workstation. 0 basics, get on the bus while it’s hot~ ~GOGOGO.

Initial environment:

window10
python3.7.6
Django3.2.3
MySQL5.6
pymysql1.0.2
PyCharm Community Edition 2019.2.3

1. Download the Django framework

Method 1: Enter in cmd: pip install -i https://pypi.douban.com/simple/ django==3.2.3

Method 2: Or find the terminal in the lower left corner of pycharm

​ Or press the shortcut key: F12 to pop up the terminal terminal window.
Enter in it: pip install -i https://pypi.douban.com/simple/ django==3.2.3
This code -I parameter specifies the use of the douban mirror and specifies the Django version.

2. Create a new Django project

I am using the community version of pycharm and cannot create a Django project, so I use the command line to create it.

Command: django-admin startproject project name [directory name]

If no directory name is specified, the system will default the directory name to be the same as the project name.

Command line 1 (cmd): django-admin startproject MyFirstWeb myfirstweb
Command line 2 (terminal terminal window): django-admin startproject MyFirstWeb myfirstweb

insert image description here

3. Run the Django project

Be sure to enter the MyFirstWeb directory (run service)
run one (cmd): python manage.py runserver
run two (terminal): python manage.py runserver

insert image description here

Close the port:
on win10: Ctrl+C
or close the process

4. Test the Django project:

Enter in the browser: http://127.0.0.1:8000
: or: localhost:8000
: you can specify the port number: 8000

insert image description here

5. Django connects to the MySQL database:

1.1 Install pymysql:

Method 1: Enter in cmd: pip install -i https://pypi.douban.com/simple/ pymysql==1.0.2

Method 2: Or find the terminal in the lower left corner of pycharm

​ Or press the shortcut key: F12 to pop up the terminal terminal window.
Enter: pip install -i https://pypi.douban.com/simple/ pymysql==1.0.2
This code -I parameter specifies the use of the douban image and specifies the pymysql version.

1.2 In the init.py file in the myfirstweb directory

import pymysql
pymysql.install_as_MySQLdb()

1.3 In the setting.py file under the myfirstweb directory, comment out the content in DATABASES and replace it with the following

DATABASES = {
    
    
	'default': {
    
    
	'ENGINE': 'django.db.backends.mysql', # 数据库的类型
	'NAME': 'django_mysql',  # 所使用的的数据库的名字
	'USER': 'root',  # 数据库服务器的用户
	'PASSWORD': '123456',  # 密码
	'HOST': '127.0.0.1',  # 主机
	'PORT': '3306',  # 端口
	}
	}

insert image description here

1.4 Generate migration files

python manage.py makemigrations

Create a database: django_mysql

To specify the database character set, otherwise an error will be reported: django.db.utils.DataError: (1366, “Incorrect string value: '\xE9\x9F\xB3\xE4\xB9\x90…' for column 'name' at row 5" )

ALTER DATABASE django_mysql CHARACTER SET utf8;

Execute the migration (at this time, the model of the application that comes with the project is mapped to the database)

python manage.py migrate

Specify the character set of the table: ALTER TABLE my_app_musicinfo CONVERT TO CHARACTER SET utf8;

1.5 Create a super administrator
python manage.py createsuperuser
Enter the user name, email, password, and confirm the password.
Since the password is too simple, press y to complete the super user creation.

6. Create your own app

1.1 Create command: python manage.py startapp my_app

1.2 Configure routing

​ 1.2.1 Add sub-routes to urls.py in the directory (change according to your own needs)

Whenever Django encounters an include() , it truncates any part of the URL that matched up to that point, and sends the remaining string into the included URLconf for further processing.

There are two key points in the above paragraph: truncate the part that has been matched, and continue to send the remaining part to the URLconf file specified by include()

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('my_app/', include('my_app.my_urls'))
]

​ 1.2.2 Add sub-routes in my_app: Create my_urls.py (change according to your own needs)

edit file:

from django.urls import path

from . import views


urlpatterns = [
    # path('', views.my_one_view),
    # path('index/', views.my_two_view),
    # path('zhuce/', views.my_three_view),
    path('DownLoad/', views.DownLoad),
    path('DownLoad_one/', views.DownLoad_one),
    path('music_list/', views.music_list),
    path('delete_music/', views.delete_music),
    path('adit_music/', views.adit_music),
    # path('upload_file/', views.upload_file, name="upload_file"),
    # path('image_file/', views.image_file, name="image_file"),
    # path('get_image_file/', views.get_image_file),
]

​1.3 Add view function in views.py of my_app
:

from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.core.exceptions import ObjectDoesNotExist,MultipleObjectsReturned
from .models import MyAppStudentinfo, Username, musicinfo
from django.template import loader
from django.db.models import *
import pymongo
import pandas as pd
import requests
import random
import time
import os
import re


# (一)模板的加载方式:通过loader获取模板,在通过HttpResponse(html)进行响应
    # t = loader.get_template('zhuche.html')
    # html = t.render()
    # return  HttpResponse(html)
    # (二)模板的加载方式:使用render直接加载并响应模板,render(request, '模板文件名', 字典数据)

    # 视图层views与templates模板层之间的交互
    # 视图层views提供: 字典数据(一定是字典)
    # templates模板层: 通过 模板语法 {
    
    {字典数据}} 调用视图层传进来的数据(变量)

    # form表单数据将提交到action='路由地址'

# 下载界面
def DownLoad(request):
    return render(request, 'DownLoad.html')


# 播放界面
def DownLoad_one(request):
    global music_info_data
    if request.method == "POST":
        search_music = request.POST.get("music_name")

        weheader = [
            ['Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'],
            ['Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2'],
            ['Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0']]

        # 使用列表推导式,生成请求头
        kk_header = [i for i in random.choice(weheader)]

        # 请求头(一定要有'User-Agent','Referer','csrf','Cookie')
        header = {
    
    
            'User-Agent': str(kk_header),
            # 'Host': 'www.kuwo.cn',
            'Referer': 'http://www.kuwo.cn/',
            'csrf': 'D32I86ILA88',
            'Cookie': '_ga=GA1.2.1490969665.1620831748; _gid=GA1.2.1678093837.1620831748; _gat=1; Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1620831749; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1620831749; kw_token=D32I86ILA88'}

        # 首页URL
        url = "http://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key={}&pn=1&rn=30" \
              "&httpsStatus=1&reqId=30709280-b333-11eb-9d41-ad2a15a69fbf".format(search_music)

        # 发送请求获取首页面
        response = requests.get(url, headers=header, timeout=30).json()

        # 获取data下面的list内容
        list_response = response['data']['list']

        # 循环获取对应内容
        for info in list_response:
            # 歌曲名
            music_name = info['name']
            # rid
            music_rid = info['rid']
            # 作者
            music_artist = info['artist']
            # 作者图像
            music_Image = info['pic']
            # 专辑
            music_album = info['album']
            # 专辑发布时间
            music_releaseDate = info['releaseDate']
            # 歌曲时长
            music_songTimeMinutes = info['songTimeMinutes']

            # 下载音乐(with open()会自动调用关闭文件,所以无需f.close())
            # with open(os.path.expanduser("~") + '\\Desktop\\music\\' + "{}.mp3".format(music_name), 'wb') as f:
            # 下载的每一首歌的URL(使用的都是统一的,rid不同)
            music_api = 'http://www.kuwo.cn/url?format=mp3&rid={}&response=url&type=convert_url3&br=128kmp3' \
                        '&from=web&t=1620883237037&httpsStatus=1&reqId=f32a4ce1-b3aa-11eb-8486-6142833c02da'.format(music_rid)

            # 将具体下载歌的response转为字典
            music_play_url = requests.get(music_api, headers=header).json()
            time.sleep(2)
            # 通过真正的URL,以二进制的形式获取
            # music_data = requests.get(music_play_url['url']).content
            # 音乐歌词URL
            geci_url = 'http://m.kuwo.cn/newh5/singles/songinfoandlrc?musicId={}'.format(music_rid)
            # 获取音乐歌词URL文本
            dome = requests.get(geci_url, headers=header, timeout=30).text
            # 通过正则表达式提取歌词数据
            music_lyric = [re.findall(r'{"lineLyric":"(.*?)","time":"(.*?)"}', dome)[i][0] for i in
                           range(len(re.findall(r'{"lineLyric":"(.*?)","time":"(.*?)"}', dome)))]

            # 以二进制形式写入文件
            # f.write(music_data)

            # 获取表,并存入表
            shujuku = musicinfo()
            shujuku.music_lyric = music_lyric
            shujuku.music_name = music_name
            shujuku.music_artist = music_artist
            shujuku.music_image = music_Image
            shujuku.music_album = music_album
            shujuku.music_releaseDate = music_releaseDate
            shujuku.music_songTimeMinutes = music_songTimeMinutes
            shujuku.music_rid = music_rid
            shujuku.music_play_url = music_play_url['url']
            shujuku.save()

            # 音乐信息内容(字典形式)
            music_info_data = {
    
    
                "music_lyric": music_lyric,
                "music_name": music_name,
                "music_artist": music_artist,
                "music_Image": music_Image,
                "music_album": music_album,
                "music_releaseDate": music_releaseDate,
                "music_songTimeMinutes": music_songTimeMinutes,
                "music_play_url": music_play_url['url'],
                # "music_data": music_data,
                "music_rid": music_rid,
            }

            print("下载成功:" + music_name)
            break
        return render(request, 'DownLoad_one.html', context=music_info_data)
    elif request.method == "GET":
        # 从请求头获取id
        huoqu_id = request.GET.get("id")
        # 在数据库进行匹配
        get_music = musicinfo.objects.get(pk=huoqu_id)
        # 音乐信息内容(字典形式)
        music_info_data = {
    
    
            "music_lyric": eval(get_music.music_lyric),
            "music_name": get_music.music_name,
            "music_artist": get_music.music_artist,
            "music_Image": get_music.music_image,
            "music_album": get_music.music_album,
            "music_releaseDate": get_music.music_releaseDate,
            "music_songTimeMinutes": get_music.music_songTimeMinutes,
            "music_play_url": get_music.music_play_url,
            "music_rid": get_music.music_rid,
        }
        return render(request, 'DownLoad_one.html', context=music_info_data)



# 音乐列表界面(思路:通过all()获取数据库所有数据all_music_s,将数据库的数据转为字典通过context传参数给"music_list.html")
def music_list(request):
    try:
        if request.method == "GET":
            # 整表聚合查询:聚合函数:Sun(),Avg(),Count(),Max(),Min()
            # 导入方法:from djanago.db.models import *
            # 返回结果为:字典{"结果变量名": 值}
            musicinfo.objects.aggregate(shuliang=Count('music_id'))
            # 分组聚合查询:
            query = musicinfo.objects.values('music_id')
            query.annotate(shuliang=Count('music_name'))
            # 获取数据库的数据
            all_music_s = musicinfo.objects.all()
            # 将数据库的数据转为字典
            data = {
    
    
                "all_music_s": all_music_s
            }
            # # context = data  # 可以传参数,也可以通过python内置函数locals()默认将函数里的所有局部变量打包成字典。
            # return render(request, "music_list.html", data)
            # return render(request, "music_list.html", context = data)
            return render(request, "music_list.html", locals())

        elif request.method == "POST":
            pass
            return render(request, "music_list.html", locals())

    except ObjectDoesNotExist and MultipleObjectsReturned:

        print("Either the blog or entry doesn't exist.")


# 删除界面(思路:从请求头获取id,通过get(pk="huoqu_id"),在数据库进行匹配,delete()执行删除)
def delete_music(request):
    # 从请求头获取id
    huoqu_id = request.GET.get("id")
    # 在数据库进行匹配
    get_music = musicinfo.objects.get(pk=huoqu_id)
    # 执行删除
    get_music.delete()
    # 功能同上
    # musicinfo.objects.get(music_id=huoqu_id).delete()
    return redirect("/my_app/music_list/")


# 编辑界面(思路:分别为两次请求(GET(获取页面所需数据)和POST))
def adit_music(request):
    try:
        if request.method == "GET":
            # 从请求头获取id
            huoqu_id = request.GET.get("id")

            # 在数据库进行匹配
            get_music = musicinfo.objects.get(pk=huoqu_id)
            return render(request, "adit_music.html",{
    
    "get_music": get_music})

        elif request.method == "POST":
            # 此时获取的数据就是用户更改的数据
            # 从请求体获取id,music_name,music_artist
            huoqu_id = request.POST.get("id")
            huoqu_music_name = request.POST.get("music_name")
            huoqu_music_artist = request.POST.get("music_artist")

            # 方法一:(更改单个数据)
            # 在数据库进行匹配,通过 QuerySet.属性 更新数据(一定要QuerySet才行)
            # Musicinfo = musicinfo.objects.get(music_id=huoqu_id)

            # # Musicinfo.music_id = huoqu_id
            # Musicinfo.music_name = huoqu_music_name
            # Musicinfo.music_artist = huoqu_music_artist
            # Musicinfo.save()

            # 方法二:(更改多个数据)
            # 在数据库进行匹配,在更新数据。(功能同上)
            musicinfo.objects.filter(music_id=huoqu_id).update(music_name=huoqu_music_name, music_artist=huoqu_music_artist)

            return redirect("/my_app/music_list/")

    except ObjectDoesNotExist and MultipleObjectsReturned:

        print("Either the blog or entry doesn't exist.")


1.4 (1) Create a templates file in my_app (for storing HTML files)

​ 1.4 (2) Find TEMPLATES in settings.py and add 'DIRS': [os.path.join(BASE_DIR, 'templates')],

insert image description here

1.4(3)外层的templates和应用下的templates都存在时
1.4(4)优先查找外层templates目录下的模板
1.4(5)按INSTALLED_APPS配置下的应用顺序逐层查找
1.4(6)为了解决同名模板文件:在各自的APP里的templates下在创建一个跟APP同名的文件夹。
1.1 创建静态文件 static
	在setting里的后面STATIC_URL = '/static/'
	添加如下:(静态文件,image,css,JavaScript)还可以写HTML
	存放在列表:STATICFILES_DIRS=[os.path.join(BASE_DIR,'static'),]
	或者存放在元组:STATICFILES_DIRS=(os.path.join(BASE_DIR,'static'),)
	# admin显示中文
	LANGUAGE_CODE = 'zh-Hans'
	# 时间
	TIME_ZONE = 'Asia/Shanghai'		
1.2 在 templates 里HTML如何使用静态文件:
	在head里加上:{% load static %}
	引用:{% static 'url' %}

​1.5 Find INSTALLED_APPS in settings.py and add 'my_app'

insert image description here

​1.6 Add a table to the models.py file

from django.db import models

class musicinfo(models.Model):
    music_id = models.BigAutoField(primary_key=True, verbose_name='ID')
    music_name = models.CharField(max_length=30, verbose_name='歌曲名')
    music_artist = models.CharField(max_length=30, verbose_name='歌手名')
    music_image = models.ImageField(max_length=1000, verbose_name='歌手图像')
    music_album = models.CharField(max_length=30, verbose_name='专辑')
    music_releaseDate = models.CharField(max_length=30, verbose_name='专辑发布时间')
    music_songTimeMinutes = models.CharField(max_length=30, verbose_name='歌曲时长')
    music_lyric = models. TextField(max_length=1000, verbose_name='歌词')
    music_rid = models.CharField(max_length=30, verbose_name='RID')
    music_play_url = models.CharField('音乐链接地址', max_length=1000)

    # 通过 Meta 内嵌类定义模型类的属性
    class Meta:
        managed = False
        # 数据库表名
        db_table = 'my_app_musicinfo'
        # 在admin中显示
        verbose_name = '音乐列表'
        # 单复数一致
        verbose_name_plural = verbose_name

    # 自定义QuerySet输出格式,在Django shell 中可以显示出详细的数据
    # from my_app.models import 表名   (exit)--退出shell
    def __str__(self):
        return "%s_%s_%s_%s_%s_%s_%s_%s_%s" % \
               (self.music_id, self.music_name, self.music_artist, self.music_image, self.music_album, self.music_releaseDate,
                self.music_songTimeMinutes, self.music_rid, self.music_play_url)


​1.6.1 Migrating the data model to the database

(1) Create a database first: django_mysql

To specify the database character set, otherwise an error will be reported: django.db.utils.DataError: (1366, “Incorrect string value: '\xE9\x9F\xB3\xE4\xB9\x90…' for column 'name' at row 5")

ALTER DATABASE django_mysql CHARACTER SET utf8;

(2) Generate a migration file (0001_initial.py will be generated)

python manage.py makemigrations my_app (my_app is the app name)
insert image description here

(3) Execute migration (at this time, map the model of the application that comes with the project to the database) and migrate to the database

python manage.py migrate
insert image description here

Be sure to specify the character set of the table: ALTER TABLE my_app_musicinfo CONVERT TO CHARACTER SET utf8;

We can also map the built database table to models.py
python manage.py inspectdb > my_app/models.py

6. ORM operation of Django

Create data (method 1: insert data clearly)
class name.objects.create(attribute 1=value 1, attribute 2=value 2)
success: return the created entity object
failure: throw an exception

Create an instance object and call save() to save it
(method 2: the data is not clear, you need to get the data)
obj = class name (attribute 1=value 1, attribute 2=value 2)
obj.attribute=value
obj.save() -- (Must be called)

Query data:
Syntax: class name.objects.all()
Function: query all data, return QuerySet container (storage object)
equivalent to SQL statement: SELECT * FROM table name;

​ Syntax: class name.objects.values()
​ Function: – Query the data of some columns and return the QuerySet container (storage dictionary)
Equivalent to SQL statement: SELECT field name 1, field name 2 FROM table name;
Syntax
: Class name.objects.values_list()
​ Function: – Query the data of some columns and return the QuerySet container (storage tuple)
​ Equivalent to SQL statement: SELECT field name 1, field name 2 FROM table name; (subscript to get data)
​​​​ Syntax
: class name.objects.order_by('-column','column')
​ Function: – Query all the data of the specified column, and return the QuerySet container (storage object) (the default is sorted in ascending order, -column is in descending order)

​ Syntax: class name.objects.exists()
​ Function: Return True if the QuerySet contains any results, and return False if it does not.
​ This function tries to execute the query in the simplest and fastest way, but it executes the query almost the same as a normal QuerySet query.
​ entry = Entry.objects.get(pk=123)
​ if some_queryset.filter(pk=entry.pk).exists():
​ print("Entry contained in queryset")

Conditional query:
Syntax: class name.objects.filter (attribute 1=value 1, attribute 2=value 2) (here the comma "and" and meaning)
function: query the data containing this condition, return the QuerySet container (storage object )
is equivalent to SQL statement: SELECT field name FROM table name WHERE condition AND condition;

Syntax: class name.objects.exclude(attribute 1=value 1)
Function: return all data not including this condition
Syntax
: class name.objects.get(attribute 1=value 1)
Function: return including this An obj object data of the condition, if there is no data (ObjectDoesNotExist)
or more than one data, an error will be reported (MultipleObjectsReturned)

Query predicate: (there are double underscores in front of the class attribute)
Syntax: class attribute __exact: equivalent matching (often used for is null)
class name.objects.filter(id__exact=1)
is equivalent to SQL statement: SELECT field name FROM table name WHERE condition;

​ Grammar: class attribute __contains: specified value matches
class name.objects.filter(name__contains="H")
​ equivalent to SQL statement: SELECT field name FROM table name WHERE name like "%H%";
Grammar
: Class attribute __startswith: Specify value matching
​ Class name.objects.filter(name__startswith="H")
​ Equivalent to SQL statement: SELECT field name FROM table name WHERE name like "H%";
Syntax
: class attribute __endswith : Specified value matching
Class name.objects.filter(name__endswith="H")
Equivalent to SQL statement: SELECT field name FROM table name WHERE name like "%H";
__gt
: greater than the specified value
__gte: greater than or equal to
__lt: Less than
__lte Less than or equal to
__in: Find whether the data is within the specified range: class name.objects.filter(name__in=["Jie Ge", "Awesome", "Awesome"]) SELECT field
name FROM Table name WHERE in ("Jiege", "Awesome", "Awesome");
__range: Find whether the data is within the specified range: class name.objects.filter(shuzi__range=(90,190))
​ SELECT field name FROM table name WHERE BETWEEN 90 AND 190;

Update a single data:
1. Check
– obtain the entity object to be modified through get()
2. Change
– modify data through the method of object.property
3. Save
– save data through object.save()

Update multiple data:
1. Check 2. Change: musicinfo.objects.filter(music_id=huoqu_id).update(music_name=huoqu_music_name, music_artist=huoqu_music_artist)

Delete a single data:
1. Check
– obtain the entity object to be modified through get()
3. Delete
– delete data through object.delete()

Delete multiple data:
1. Check 2. Change: musicinfo.objects.filter(music_id=huoqu_id).delete()
Pseudo-deletion:
1. In the models.py file, when creating a database table, add
a boolean to the field Field is_active=models.BooleanField("Active", default=True) True (default is True)
When performing deletion, set the is_active field of the data to be deleted to False.
Note: When using pseudo-delete, make sure to add is_active=True filtering query where the data is displayed.

7. Admin background management:

​ Register a custom model class:
​ (If you want to display and manage your own defined model class in the admin background management interface,
you need to register your own class to the background management interface)

1. 在APP中的admin.py中导入注册要管理的模型models类
	from .models import musicinfo
2. 调用admin.site.register()方法进行注册
	admin.site.register(musicinfo)
	
3. ```python
  from django.contrib import admin
  from .models import musicinfo
  # Register your models here.
  
  
  class musicinfoManager(admin.ModelAdmin):
      # 列表页显示哪些字段的列
      list_display = ['music_id' ,'music_name', 'music_artist', 'music_image',
                      'music_album', 'music_releaseDate', 'music_songTimeMinutes',
                      'music_rid', 'music_play_url']
      # 控制 list_display 中的哪些字段可以超链接到修改页(添加的字段必须是 list_display 里面的)
      list_display_links = ['music_name']
      # 添加过滤器
      list_filter = ['music_artist']
      # 添加搜索框[模糊查询]
      search_fields = ['music_name', 'music_artist']
      # 添加可在列表页编辑字段与 list_display_links 不能共存
      # list_editable = ['']
  admin.site.register(musicinfo, musicinfoManager)
  ```

Model manager class:
Function: Add new functions for easy operation to the background management interface
Note: The background management class must inherit the ModelAdmin class in Django.contrib.admin

Pieces of notes:

Quickly arrange codes: shortcut key: ctrl+shift+alt+L
to zoom in on the admin interface shortcut key: ctrl++

Run python3 manage.py directly to list all django subcommands

Django looks for files based on routing, looking for paths

When using url:
use it for testing yourself: absolute path

​ When using a relative path: the routing browser with '/' will default to the final access address in the current address bar (protocol + IP + port number).

URL reverse parsing: refers to using the name defined by path to dynamically find or calculate the corresponding route in the view or template.
path('/luyou/', views.luyou, name='unique name')
{% url 'unique name' 'parameter value 1' 'parameter value 2' %}
{% url 'unique name' id='1' name='jiege' %}==127.0.0.1:8000/xxx/xxx/?id=1&name=jiege

Instance object = musicinfo.objects.filter().get().update()
print(instance object.query) # translate into SQL statement

Enter the Django shell environment: python manage.py shell

able = [’’]
admin.site.register(musicinfo, musicinfoManager)
```

Model manager class:
Function: Add new functions for easy operation to the background management interface
Note: The background management class must inherit the ModelAdmin class in Django.contrib.admin

Pieces of notes:

Quickly arrange codes: shortcut key: ctrl+shift+alt+L
to zoom in on the admin interface shortcut key: ctrl++

Run python3 manage.py directly to list all django subcommands

Django looks for files based on routing, looking for paths

When using url:
use it for testing yourself: absolute path

​ When using a relative path: the routing browser with '/' will default to the final access address in the current address bar (protocol + IP + port number).

URL reverse parsing: refers to using the name defined by path to dynamically find or calculate the corresponding route in the view or template.
path('/luyou/', views.luyou, name='unique name')
{% url 'unique name' 'parameter value 1' 'parameter value 2' %}
{% url 'unique name' id='1' name='jiege' %}==127.0.0.1:8000/xxx/xxx/?id=1&name=jiege

Instance object = musicinfo.objects.filter().get().update()
print(instance object.query) # translate into SQL statement

Enter the Django shell environment: python manage.py shell

Write models.ImageField(max_length=30) on models and you may need to download pillow

References:
Python version corresponding to Django: https://docs.djangoproject.com/en/3.2/faq/install/#faq-python-version-support
https://www.cnblogs.com/xiaoqingSister/p/13355832 .html
https://www.bilibili.com/video/BV1vK4y1o7jH

This article is for personal reference only, non-commercial use, it refers to other literature, if there is anything inappropriate, please contact me
email: [email protected]

Guess you like

Origin blog.csdn.net/weixin_49237144/article/details/117618580