您的位置:首页 > 数据库 > SQL

django+mysql+插入数据库网页展示内容

2017-11-03 21:03 946 查看
版本:Django version 1.11.6

python:2.7

目录结构



model

首先,需要写model,即你需要操作的数据。

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
# Create your models here.
class message(models.Model):
username = models.CharField(max_length=20)
password = models.CharField(max_length=15)


setting中添加



同时修改:

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']




这里添加的是数据的地址,端口,用户名及密码,库名。

将下面的注释掉,防止出现错误。



创建数据库



运行下面的命令自动创建数据库:





views.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_web import models
from django.shortcuts import render

#插入函数
def insert(request):
if request.method == "POST":
username = request.POST.get("username", None)
password = request.POST.get("password", None)
twz = models.message.objects.create(username=username, password=password)
twz.save()
return render(request,'insert.html')

#定义展示函数
def list(request):
people_list = models.message.objects.all()
return render(request, 'show.html', {"people_list":people_list})


insert.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<form action="/insert/" method="post"> {% csrf_token %}
<input type="text" name="username"/>
<input type="password" name="password"/>
<input type="submit" value="提交">
</form>
</body>
</html>


show.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>信息展示</h1>
<table>
<tr>
<th>用户名</th>
<th>密码</th>
</tr>
{% for line in people_list %}
<tr>
<td>{{line.username}}</td>
<td>{{line.password}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>


urls.py

from django.conf.urls import url
from django.contrib import admin
from django_web import views

urlpatterns = [
url(r'^insert/$',views.insert),
url(r'^show/$',views.list),
url(r'^admin/', admin.site.urls),
]


运行程序



网页打开



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: