当前位置:网站首页> 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 makemigrationspython 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使用内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!
边栏推荐
- The so-called consumer Internet only matches and connects industry information, and does not change the industry itself
- Introduction to the internal structure of the data directory of PostgreSQL
- AWS learning notes (I)
- MySQL
- C # / vb. Net supprime le filigrane d'un document word
- 哈希表及完整注释
- QT常见概念-1
- B站6月榜单丨飞瓜数据UP主成长排行榜(哔哩哔哩平台)发布!
- leetcode:736. LISP syntax parsing [flowery + stack + status enumaotu + slots]
- What to do when encountering slow SQL? (next)
猜你喜欢

Hash table and full comments
![[paper reading | deep reading] anrl: attributed network representation learning via deep neural networks](/img/06/17acf9958228cce5d80ada3275ad24.png)
[paper reading | deep reading] anrl: attributed network representation learning via deep neural networks

fiddler的使用

Five reasons for clothing enterprises to deploy MES management system

leetcode:736. Lisp 语法解析【花里胡哨 + 栈 + 状态enumaotu + slots】

postgresql之整體查詢大致過程

S120驱动器基本调试步骤总结

Draco - gltf model compression tool

unity中跟随鼠标浮动的面板,并可以自适应文字内容的大小

Electrical engineering and automation
随机推荐
Wireshark installation
安德鲁斯—-多媒体编程
wireshark安装
Pioneer of Web3: virtual human
[Mori city] random talk on GIS data (II)
C#/VB. Net to delete watermarks in word documents
The panel floating with the mouse in unity can adapt to the size of text content
What are the applications and benefits of MES management system
Fundamentals of process management
How to build a 32core raspberry pie cluster from 0 to 1
Electrical engineering and automation
Mmdetection3d loads millimeter wave radar data
Hash table and full comments
MySQL --- 常用函数 - 字符串函数
基于ensp防火墙双击热备二层网络规划与设计
C # / vb. Net supprime le filigrane d'un document word
1 -- Xintang nuc980 nuc980 porting uboot, starting from external mx25l
Common fitting models and application methods of PCL
QPushButton-》函数精解
fasterxml ToStringSerializerBase报错