当前位置:网站首页>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 mysiteAfter 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 blogAfter completion , A... Will be generated in the project blog Folder

Initialize 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 createsuperuserBe 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 runserverDefault 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 makemigrationspython 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 :

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 :



This 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 !
边栏推荐
- 普通测试年薪15w,测试开发年薪30w+,二者差距在哪?
- Integerset of PostgreSQL
- Unity custom webgl packaging template
- Difference and the difference between array and array structure and linked list
- Compress JS code with terser
- 人脸识别应用解析
- Dotconnect for DB2 Data Provider
- 一本揭秘字节万台节点ClickHouse背后技术实现的白皮书来了!
- How to design interface test cases? Teach you a few tips to draft easily
- unity webgl自适应网页尺寸
猜你喜欢

服装企业部署MES管理系统的五个原因

Statistics of radar data in nuscenes data set

普通测试年薪15w,测试开发年薪30w+,二者差距在哪?

Station B's June ranking list - feigua data up main growth ranking list (BiliBili platform) is released!
![leetcode:5. Longest palindrome substring [DP + holding the tail of timeout]](/img/62/d4d5428f69fc221063a4f607750995.png)
leetcode:5. Longest palindrome substring [DP + holding the tail of timeout]

实施MES管理系统时,哪些管理点是需要注意的

Increase 900w+ playback in 1 month! Summarize 2 new trends of top flow qiafan in station B

Linear list --- circular linked list

Five reasons for clothing enterprises to deploy MES management system

Go swagger use
随机推荐
Application analysis of face recognition
Error in fasterxml tostringserializerbase
服装企业部署MES管理系统的五个原因
STM32 project -- Topic sharing (part)
[C # notes] reading and writing of the contents of text files
Summer Challenge database Xueba notes (Part 2)~
LeetCode 77:组合
What are the characteristics of the operation and maintenance management system
CDB PDB user rights management
用全连接+softmax对图片的feature进行分类
The 8 element positioning methods of selenium that you have to know are simple and practical
Leetcode:minimum_depth_of_binary_tree解决问题的方法
导数、偏导数、方向导数
Linear list --- circular linked list
Five reasons for clothing enterprises to deploy MES management system
测试优惠券要怎么写测试用例?
PCL 常用拟合模型及使用方法
Ali yunyili: how does yunyuansheng solve the problem of reducing costs and improving efficiency?
【Node学习笔记】chokidar模块实现文件监听
widerperson数据集转化为YOLO格式