在templates目录下新建一个t1.html的文件,内容如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Django操作数据库</title> <link type="text/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" 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使用内容请搜索
标签:SQLite
相关阅读 >>
更多相关阅读请进入《Sqlite》频道 >>

数据库系统概念 第6版
本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。