[Django 2021 latest edition tutorial 8] Operating Mysql database mysqlclient installation and use

1. Installation

1. Install mysql

It is recommended to download phpstudy under windows, one-click installation, specific operation Baidu: phpstudy installation tutorial

Note down the account password for database login during installation.

After the installation is successful, as follows

Please make sure that the mysql version is greater than 5.6 . If it is not greater, an error will be reported in django and you need to upgrade mysql. Please refer to https://shijianfeng.blog.csdn.net/article/details/117428669 .

After everything is okay,

Create a new database, the name is visit_tsinghua, and the encoding must be utf8-general-ci, otherwise Chinese storage is not supported

2. Install mysqlclient2.0.3

After the installation is successful, you can see it outside

Two, use mysql in the Django framework

1. Modify the contents of DATABASES in settings.py as follows:

DATABASES = {    'default': {        'ENGINE': 'django.db.backends.mysql',        'NAME': 'visit_tsinghua',        'USER': 'root',        'PASSWORD': 'root',        'HOST': '',        'PORT': '3306',        'OPTIONS': {            "init_command": "SET sql_mode='STRICT_TRANS_TABLES'",        }    }}

Where NAME is your database name, HOST is the database address, everyone knows the others.

2. Enter models.py to create an object model corresponding to your database table

from django.db import modelsclass User(models.Model):    id = models.AutoField(primary_key=True) # django 在每一次save()操作后都可以正常的增加一条数据并且id顺序自增。id无需在save中创建,数据表自动添加    name = models.CharField(max_length=50)    level = models.IntegerField(default=1) # 用户等级,默认1    createTime = models.DateTimeField(null=True)    class Meta:        db_table = 'User' # 数据表名称

Enter the same level directory of manage.py from the command line

Execute python manage.py makemigratetions app name (optional)

# 让 Django 知道我们在我们的模型有一些变更python manage.py makemigrations userWeb


# 创建表结构python manage.py migrate

Check the database and find that the user table has been created.

This is called ORM, Object Relation Mapping, which implements the mapping between objects and databases, hides the details of data access, and does not need to write SQL statements

Models of multiple tables can be created in models.py.

3. Register the model in admin.py

from django.contrib import adminfrom . import models # Register your models here.admin.site.register(models.User)

4. TestUser.html is the front-end page placed in templates:

<!DOCTYPE html><html><body><p>请输入用户信息</p><form action="/testadduser" method="post">    {%csrf_token%}    姓名: <input type="text" name="name"> <br>    用户等级: <input type="number" name="level"> <br>    <input type="submit" value="提交"></form></body></html>

5. The code written in views.py (or the py file created by yourself) mainly depends on the testAddUser method:

import datetime from django.http import HttpResponsefrom django.shortcuts import render # Create your views here.from userWeb.models import User  def index(request):    return render(request, './userWeb/index.html') # 加法页面def add(request):    return render(request, './userWeb/add.html') # 执行加法def doadd(request):    a = request.POST['a']    b = request.POST['b']    a = int(a)    b = int(b)    result = a + b    # return HttpResponse(str(result))    context = {}    context['a'] = a    context['b'] = b    context['result'] = result    return render(request, './userWeb/add_result.html', context) # 增加用户页面def testUser(request):    return render(request, './userWeb/testUser.html') def testAddUser(request):     name = request.POST['name']    level = request.POST['level']    createTime = datetime.datetime.now()     user = User.objects.create(name=name, level=level, createTime=createTime)     context = {}    context['msg'] = '用户新增成功'    context['数据库中的id'] = user.id    return HttpResponse(str(context))

6. Add the complete code of the path to urls.py as follows:

"""visit_tsinghua URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see:    https://docs.djangoproject.com/en/3.2/topics/http/urls/Examples:Function views    1. Add an import:  from my_app import views    2. Add a URL to urlpatterns:  path('', views.home, name='home')Class-based views    1. Add an import:  from other_app.views import Home    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')Including another URLconf    1. Import the include() function: from django.urls import include, path    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))"""from django.contrib import adminfrom django.urls import pathfrom userWeb.views import * urlpatterns = [    path('admin/', admin.site.urls),    path('index', index),    path("add", add),    path("doadd", doadd),    path("testuser", testUser),    path("testadduser", testAddUser),]

7. Operation effect