当前位置:网站首页>Django database (SQLite) basic introductory tutorial
Django database (SQLite) basic introductory tutorial
2022-07-07 02:44:00 【1024 questions】
1: Create a project
2: establish blog application
3: Database operation
4. stay blog_demo Add data to table :
summary
1: Create a projectdjango-admin startproject mysite
After creation , The structure of the project catalogue is as follows :
manage.py ----- Django Tools in the project , It allows you to call django shell And database, etc .
settings.py ---- Contains the default settings for the project , Include database information , Debug flags and other working variables .
urls.py ----- Responsible for the URL Schema mapping to application .
2: establish blog applicationpython manage.py startapp blog
After completion , A... Will be generated in the project blog Folder
3: Database operationInitialize database :
python Bring their own SQLite database ,Django Support various mainstream databases , Here we first use SQLite.
If you use other databases, please use settings.py Set in file . The default configuration of the database is :
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}
Use the default data configuration to initialize the database :
After command execution , Some data tables will be generated :
Django I have a WEB backstage , Create below WEB Background user name and password :
python manage.py createsuperuser
Be careful ️: The password cannot be similar to the user name , Passwords cannot be pure numbers .
Next, let's use the account and password created above to log in to the background . To log in to the background , Must be in settings.py File will be created above APP That is to say blog added :
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog',]
Note that there must be a comma after it !
start-up django Containers :
python manage.py runserver
Default WEB The address is http://127.0.0.1, Port is 8000, Use this address and port to access the home page :
Next visit django The background of :http://127.0.0.1/admin
Create a UseInfo surface , And create fields :
Now let's open up blog In the catalog models.py file , This is what we define blog Where data structures . open mysite/blog/models.py File modification :
from django.db import models# Create your models here.class Demo(models.Model): car_num = models.CharField(max_length=32) park_name = models.CharField(max_length=32) jinru_Date = models.CharField(max_length=32) chuqu_Date = models.CharField(max_length=32) time = models.CharField(max_length=32)
Command line execution :
python manage.py makemigrations
python manage.py migrate
As can be seen from the above figure ,Django By default, the APP Named data table prefix , Take the class name as the data table name !
The fields created are shown in the following figure :
4. stay blog_demo Add data to table :Django Is in views.py In file , By importing models.py Documents come Create data Of :
from django.shortcuts import render# Create your views here.from blog import models # Import blog modular from django.shortcuts import HttpResponsedef db_handle(request): # Add data models.Demo.objects.create(car_num=' shan E-BV886', park_name=' Hospital of traditional Chinese medicine ', jinru_Date='2022-02-05', chuqu_Date='2022-02-06', time='1') return HttpResponse('OK')
Now let's configure the route , So that the browser can access views.py file :
from blog import viewsurlpatterns = [ path('admin/', admin.site.urls), path(r'db_handle', views.db_handle),]
Let's visit http://127.0.0.1/db_handle
Check whether the database is created successfully :
Above is Create table data , You can also create table data in the format of a dictionary :
def db_handle(request): dic = {car_num=' shan E-BV886', park_name=' Hospital of traditional Chinese medicine ', jinru_Date='2022-02-05',chuqu_Date='2022-02-06', time='1'} models.Demo.objects.create(**dic) return HttpResponse('OK')
Delete table data :
views.py The documents are as follows :
def db_handle(request): # Delete table data models.Demo.objects.filter(id=1).delete() return HttpResponse('OK')
The operation method is the same as above , Execute it once in the browser , In the data id=1 The data of is deleted :
Modify table data :
def db_handle(request): # Modify table data models.Demo.objects.filter(id=2).update(time=18) return HttpResponse('OK')
Data query :
In order to display the queried data more intuitively , Here we will use Django The template function of , Let the queried data in WEB Displayed in the browser
stay templates Create a new one in the directory t1.html The file of , The contents are as follows :
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Django Operating the database </title> <link type="text/css" href="/static/base.css" rel="external nofollow" rel="external nofollow" rel="stylesheet" /></head><body> <table border="1"> <tr> <th> license plate number </th> <th> Parking lot name </th> <th> Admission time </th> <th> Playing time </th> <th> Parking Duration </th> </tr> {% for item in li %} <tr> <td>{{ item.car_num }}</td> <td>{{ item.park_name }}</td> <td>{{ item.jinru_Date }}</td> <td>{{ item.chuqu_Date }}</td> <td>{{ item.time }}</td> </tr> {% endfor %}</body></html>
views.py File query data , And specify the template file to call , The contents are as follows :
def db_handle(request): user_list_obj = models.Demo.objects.all() return render(request, 't1.html', {'li': user_list_obj})
Be careful : Because this is under the project templates The template created under the directory , Not in blog Templates created in the application , above views.py Invoked in file t1.html Templates , When it runs, it will appear that it cannot be found t1.html Template error , In order to find mysite/templates Under the template file , We still need to settings.py Path of file configuration template :
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], # Configure template path 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]
Now you can view it in the browser :
introduce JS,CSS Etc. static files :
stay mysite Create a new one in the directory static Catalog , take JS,CSS Files are placed in this directory ! And in settings.py The document specifies static Catalog :
STATIC_URL = '/static/'STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'),)
Form submission data :
stay Django To be used in post Submit form by , Need to be in settings.py Comment out the following line in the configuration file :
# 'django.middleware.csrf.CsrfViewMiddleware',
Submit Form ( It's still used here t1.html):
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Django Operating the database </title> <link type="text/css" href="/static/base.css" rel="external nofollow" rel="external nofollow" rel="stylesheet" /></head><body> <table border="1"> <tr> <th> license plate number </th> <th> Parking lot name </th> <th> Admission time </th> <th> Playing time </th> <th> Parking Duration </th> </tr> {% for item in li %} <tr> <td>{{ item.car_num }}</td> <td>{{ item.park_name }}</td> <td>{{ item.jinru_Date }}</td> <td>{{ item.chuqu_Date }}</td> <td>{{ item.time }}</td> </tr> {% endfor %} </table> <form action="/db_handle" method="post"> <p><input name="car_num" /></p> <p><input name="park_name" /></p> <p><input name="jinru_Date" /></p> <p><input name="chuqu_Date" /></p> <p><input name="time" /></p> <p><input type="submit" value="submit" /></p> </form></body></html>
Write to database (views.py):
def db_handle(request): if request.method == "POST": models.Demo.objects.create(car_num=request.POST['car_num'],park_name=request.POST['park_name'],jinru_Date=request.POST['jinru_Date'],chuqu_Date=request.POST['chuqu_Date'],time=request.POST['time']) user_list_obj = models.Demo.objects.all() return render(request, 't1.html', {'li': user_list_obj})
After submitting the data , Here's the picture :
summaryThis is about Django database (SQlite) This is the article of the basic introductory tutorial , More about Django database SQlite Please search the previous articles of SDN or continue to browse the relevant articles below. I hope you can support SDN in the future !
边栏推荐
- 1 -- Xintang nuc980 nuc980 porting uboot, starting from external mx25l
- 进程管理基础
- CDB PDB user rights management
- 所谓的消费互联网仅仅只是做行业信息的撮合和对接,并不改变产业本身
- The annual salary of general test is 15W, and the annual salary of test and development is 30w+. What is the difference between the two?
- Dotconnect for DB2 Data Provider
- 1--新唐nuc980 NUC980移植 UBOOT,从外部mx25l启动
- Argo workflows source code analysis
- MATLB|具有储能的经济调度及机会约束和鲁棒优化
- Classify the features of pictures with full connection +softmax
猜你喜欢
Increase 900w+ playback in 1 month! Summarize 2 new trends of top flow qiafan in station B
S120驱动器基本调试步骤总结
电气工程及其自动化
普通测试年薪15w,测试开发年薪30w+,二者差距在哪?
Google Earth Engine(GEE)——Landsat 全球土地调查 1975年数据集
LeetCode 77:组合
Cloud Mail . NET Edition
Fundamentals of process management
What management points should be paid attention to when implementing MES management system
3 -- Xintang nuc980 kernel supports JFFS2, JFFS2 file system production, kernel mount JFFS2, uboot network port settings, and uboot supports TFTP
随机推荐
Untiy文本框的代码换行问题
wzoi 1~200
牛客编程题--必刷101之双指针篇
The cities research center of New York University recruits master of science and postdoctoral students
[unity notes] screen coordinates to ugui coordinates
慧通编程入门课程 - 2A闯关
MySQL
The annual salary of general test is 15W, and the annual salary of test and development is 30w+. What is the difference between the two?
【软件测试】最全面试问题和回答,全文背熟不拿下offer算我输
C # / vb. Net supprime le filigrane d'un document word
Use of pgpool II and pgpooladmin
Summer Challenge database Xueba notes (Part 2)~
软件测试——Jmeter接口测试之常用断言
Remember the problem analysis of oom caused by a Jap query
This week's hot open source project!
【Node学习笔记】chokidar模块实现文件监听
B站6月榜单丨飞瓜数据UP主成长排行榜(哔哩哔哩平台)发布!
Fundamentals of process management
数字滚动增加效果
Derivative, partial derivative, directional derivative