当前位置:网站首页> Django数据库(SQlite)基本入门使用教程
Django数据库(SQlite)基本入门使用教程
2022-07-06 19:08:00 【1024问】
1:创建工程
2:创建blog应用
3:数据库操作
4.在blog_demo表中添加数据:
总结
1:创建工程django-admin startproject mysite
创建完成后,工程目录结构如下:
manage.py ----- Django项目里面的工具,通过它可以调用django shell和数据库等。
settings.py ---- 包含了项目的默认设置,包括数据库信息,调试标志以及其他一些工作的变量。
urls.py ----- 负责把URL模式映射到应用程序。
2:创建blog应用python manage.py startapp blog
完成后,会在项目中生成一个blog的文件夹
初始化数据库:
python 自带SQLite数据库,Django支持各种主流的数据库,这里我们首先使用SQLite。
如果使用其它数据库请在settings.py文件中设置。数据库默认的配置为:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}
使用默认的数据配置来初始化数据库:
命令执行完成后,会生成一些数据表:
Django自带有一个WEB 后台,下面创建WEB后台的用户名与密码:
python manage.py createsuperuser
注意️:密码不能与用户名相似,密码不能纯数字 。
接下来我们使用上面创建的账号密码登录后台试试。要登录后台,必须在settings.py文件中将上面创建的APP也就是blog添加进来:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog',]
注意后面必须要有个逗号!
启动django容器:
python manage.py runserver
默认使用的WEB地址为http://127.0.0.1,端口为8000,使用该地址与端口访问首页:
下面访问django的后台:http://127.0.0.1/admin
创建一张UseInfo表,并创建字段:
现在我们打开blog目录下的models.py文件,这是我们定义blog数据结构的地方。打开mysite/blog/models.py 文件进行修改:
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)
命令行执行:
python manage.py makemigrations
python manage.py migrate
从上图中可以看出,Django默认会以APP名为数据表前缀,以类名为数据表名!
创建的字段如下图:
Django是在views.py文件中,通过导入models.py文件来创建数据的:
from django.shortcuts import render# Create your views here.from blog import models # 导入blog模块from django.shortcuts import HttpResponsedef db_handle(request): # 添加数据 models.Demo.objects.create(car_num='陕E-BV886', park_name='中医院', jinru_Date='2022-02-05', chuqu_Date='2022-02-06', time='1') return HttpResponse('OK')
下面我们配置路由,以便让浏览器能够访问到views.py文件:
from blog import viewsurlpatterns = [ path('admin/', admin.site.urls), path(r'db_handle', views.db_handle),]
下面我们来访问http://127.0.0.1/db_handle
查看数据库是否创建成功:
上面就是创建表数据,也可以通过字典的格式来创建表数据:
def db_handle(request): dic = {car_num='陕E-BV886', park_name='中医院', jinru_Date='2022-02-05',chuqu_Date='2022-02-06', time='1'} models.Demo.objects.create(**dic) return HttpResponse('OK')
删除表数据:
views.py文件如下:
def db_handle(request): #删除表数据 models.Demo.objects.filter(id=1).delete() return HttpResponse('OK')
操作方法同上,在浏览器中执行一遍,数据中的id=1的数据即被删除:
修改表数据:
def db_handle(request): # 修改表数据 models.Demo.objects.filter(id=2).update(time=18) return HttpResponse('OK')
数据的查询:
为了让查询出来的数据更加直观地显示出来,这里我们将使用Django的模板功能,让查询出来的数据在WEB浏览器中展示出来
在templates目录下新建一个t1.html的文件,内容如下:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Django操作数据库</title> <link type="text/css" href="/static/base.css" rel="external nofollow" rel="external nofollow" rel="stylesheet" /></head><body> <table border="1"> <tr> <th>车牌号</th> <th>停车场名</th> <th>入场时间</th> <th>出场时间</th> <th>停车时间</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文件查询数据,并指定调用的模板文件,内容如下:
def db_handle(request): user_list_obj = models.Demo.objects.all() return render(request, 't1.html', {'li': user_list_obj})
注意:由于这里是在工程下面的templates目录下建立的模板,而不是在blog应用中创建的模板,上面views.py文件中调用的t1.html模板,运行时会出现找不到t1.html模板的错误,为了能找到mysite/templates下的模板文件,我们还需要在settings.py文件配置模板的路径:
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], # 配置模板路径 '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', ], }, },]
下面就可以在浏览器中查看:
引入JS,CSS等静态文件:
在mysite目录下新建一个static目录,将JS,CSS文件都放在此目录下!并在settings.py文件中指定static目录:
STATIC_URL = '/static/'STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'),)
表单提交数据:
在Django中要使用post方式提交表单,需要在settings.py配置文件中将下面一行的内容给注释掉:
# 'django.middleware.csrf.CsrfViewMiddleware',
提交表单(这里仍然使用了t1.html):
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Django操作数据库</title> <link type="text/css" href="/static/base.css" rel="external nofollow" rel="external nofollow" rel="stylesheet" /></head><body> <table border="1"> <tr> <th>车牌号</th> <th>停车场名</th> <th>入场时间</th> <th>出场时间</th> <th>停车时间</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>
写入数据库(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})
提交数据后,如下图:
到此这篇关于Django数据库(SQlite)基本入门使用教程的文章就介绍到这了,更多相关Django数据库SQlite使用内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!
边栏推荐
- Difference and the difference between array and array structure and linked list
- postgresql之整體查詢大致過程
- CSDN 夏令营课程 项目分析
- MySQL
- 基于ensp防火墙双击热备二层网络规划与设计
- Derivative, partial derivative, directional derivative
- 【森城市】GIS数据漫谈(二)
- C#/VB.NET 删除Word文檔中的水印
- Halcon instance to opencvsharp (C openCV) implementation -- bottle mouth defect detection (with source code)
- Argo workflows source code analysis
猜你喜欢
Argo workflows source code analysis
Application analysis of face recognition
Integerset of PostgreSQL
Electrical engineering and automation
Google Earth Engine(GEE)——Landsat 全球土地调查 1975年数据集
This week's hot open source project!
MMDetection3D加载毫米波雷达数据
Hash table and full comments
Data connection mode in low code platform (Part 1)
unity 自定义webgl打包模板
随机推荐
Overall query process of PostgreSQL
如何设计好接口测试用例?教你几个小技巧,轻松稿定
Application analysis of face recognition
What are the applications and benefits of MES management system
CDB PDB 用户权限管理
[paper reading | deep reading] graphsage:inductive representation learning on large graphs
测试优惠券要怎么写测试用例?
Cloud Mail .NET Edition
Lombok makes the pit of ⽤ @data and @builder at the same time
unity中跟随鼠标浮动的面板,并可以自适应文字内容的大小
4 -- Xintang nuc980 mount initramfs NFS file system
MySQL --- 常用函数 - 字符串函数
This week's hot open source project!
MFC Windows 程序设计[147]之ODBC数据库连接(附源码)
1--新唐nuc980 NUC980移植 UBOOT,从外部mx25l启动
Real project, realized by wechat applet opening code (end)
[unity] upgraded version · Excel data analysis, automatically create corresponding C classes, automatically create scriptableobject generation classes, and automatically serialize asset files
ODBC database connection of MFC windows programming [147] (with source code)
Untiy文本框的代码换行问题
NuScenes数据集关于Radar数据的统计