表单数据库案例
1. 进入数据库:
Mysql –u root –p
2. 创建数据库:
Create database userdb default charset urf8 collate utf8_general_ci;
3. 进入models.py文件创建model
4. 进入settings.py文件配置数据库
5. 进入__init__.py文件配置信息
6. 启动应用程序:./manage.py makemigrations ./manage.py migrate
7. 创建login.html文件
8. 进入urls.py文件配置路由信息
9. 进入views.py文件
views.py文件
from django.shortcuts import render
from django.http import HttpResponse
from .models import *
# Create your views here.
def show_request_views(request):
# print(dir(request))
scheme = request.scheme
body = request.body
path = request.path
method = request.method
host = request.get_host()
get = request.GET
post = request.POST
cookie = request.COOKIES
meta = request.META
return render(request, 'show_request.html', locals())
def show_get_views(request):
# 获取get请求提交的数据
get = request.GET
# name = request.GET['name']
# age = request.GET['age']
if 'name' in request.GET:
name = request.GET['name']
if 'age' in request.GET:
age = request.GET['age']
return render(request, 'show_get.html', locals())
def login_views(request):
# 判断是post请求还是get请求,来分析用户的意图
if request.method == 'GET':
return render(request, 'login.html')
else:
return HttpResponse('处理数据!')
def register_views(request):
if request.method == 'GET':
return render(request, 'register.html')
else:
if 'uname' in request.POST:
uname = request.POST['uname']
if 'upwd' in request.POST:
upwd = request.POST['upwd']
if 'uemail' in request.POST:
uemail = request.POST['uemail']
Users.objects.create(uname=uname, upass=upwd, uemail=uemail)
return HttpResponse("Regist Success!")
urls.py文件
from django.conf.urls import url
from .views import *
urlpatterns = [
url(r'^show_request/$', show_request_views),
url(r'^show_get/$', show_get_views),
url(r'^login/', login_views,name='login'),
url(r'^register/$',register_views),
]
login.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="{%url 'login'%}" method="post">
{%csrf_token%}
<p>
用户名称:
<input type="text" name="uname">
</p>
<p>
用户密码:
<input type="password" name="upwd">
</p>
<p>
<input type="submit" value="登录">
</p>
</form>
</body>
</html>
init.py文件
import pymysql
pymysql.install_as_MySQLdb()
settings.py文件
"""
Django settings for day7 project.
Generated by 'django-admin startproject' using Django 1.11.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0_5h3jijlpn95xr!sliezuek^vl@#gx5j=)+3ha((z2my3d+22'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'index',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'day7.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'day7.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'userdb',
'USER': 'root',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
models.py文件
from django.db import models
# Create your models here.
class Users(models.Model):
uname = models.CharField(max_length=30)
upass = models.CharField(max_length=30)
uemail = models.EmailField()
view.py文件
from django.shortcuts import render
from django.http import HttpResponse
from .models import *
# Create your views here.
def show_request_views(request):
# print(dir(request))
scheme = request.scheme
body = request.body
path = request.path
method = request.method
host = request.get_host()
get = request.GET
post = request.POST
cookie = request.COOKIES
meta = request.META
return render(request, 'show_request.html', locals())
def show_get_views(request):
# 获取get请求提交的数据
get = request.GET
# name = request.GET['name']
# age = request.GET['age']
if 'name' in request.GET:
name = request.GET['name']
if 'age' in request.GET:
age = request.GET['age']
return render(request, 'show_get.html', locals())
def login_views(request):
# 判断是post请求还是get请求,来分析用户的意图
if request.method == 'GET':
return render(request, 'login.html')
else:
return HttpResponse('处理数据!')
def register_views(request):
if request.method == 'GET':
return render(request, 'register.html')
else:
if 'uname' in request.POST:
uname = request.POST['uname']
if 'upwd' in request.POST:
upwd = request.POST['upwd']
if 'uemail' in request.POST:
uemail = request.POST['uemail']
Users.objects.create(uname=uname, upass=upwd, uemail=uemail)
return HttpResponse("Regist Success!")
# 1.创建数据库 usersdb
# 2.创建模型 users
# uname, upass, uemail
# 映射到数据库中
# 3.提供一个 register.html
# 一个文本框,一个密码框,一个Email框,一个提交按钮
# 4.点击提交按钮时,提交给 /login/ 处理注册信息
# 获取文本框,密码框,Email框的值,并插入到数据库中
# 5.输入 http://localhost:8000/login 显示注册页面