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

版本:Django version 1.11.6
python:2.7

目录结构

django+mysql+插入数据库网页展示内容_第1张图片

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中添加

django+mysql+插入数据库网页展示内容_第2张图片

同时修改:

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

ALLOWED_HOSTS = ['*']

django+mysql+插入数据库网页展示内容_第3张图片

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

将下面的注释掉,防止出现错误。
django+mysql+插入数据库网页展示内容_第4张图片

创建数据库

django+mysql+插入数据库网页展示内容_第5张图片

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

django+mysql+插入数据库网页展示内容_第6张图片

django+mysql+插入数据库网页展示内容_第7张图片

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


<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


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
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),
]

运行程序

django+mysql+插入数据库网页展示内容_第8张图片

网页打开

django+mysql+插入数据库网页展示内容_第9张图片

django+mysql+插入数据库网页展示内容_第10张图片

你可能感兴趣的:(python,Python3开发)