Django模板和Django使用cookie
文章目录
- 本文代码已上传[代码连接轻点此处](https://download.csdn.net/download/qq\_32460819/12179139)
- 说明:
- 一、创建魔板
- 二、上传数据
- 三、创建数据上传完成提示, 使用form魔板
- 新建forms.py
- 2.HTML调用forms.py
- views.py
- 4 urls.py请求与反馈
- 四、cookie
- 1 test_cookie.html
- 2 views.py 设置cookie
- 3 urls.py调用
- 4 结果
本文代码已上传代码连接轻点此处
说明:
- 首先创建好通用魔板,即完成数据库,跟后台APP
- 首先浏览器访问服务器, url(r’^first_test/$’, first_test), first_test先返回html界面
- 用户在向html界面传递数据, 于是服务器根据传递的参数传递回first_test函数, 这个时候才开始处理数据
- 处理数据包含将用户提交的数据上传到服务器
- 因为界面包含的按钮跳转jqAjax()函数,该函数执行url=http://127.0.0.1:8000/post\_data/
- 因此又跳转到post_data请求,
- 而该请求仅仅将成功请求标识返回来,于是界面进行了反馈显示
- 所以从用户请求到最终用了 1请1显(请求显示界面) 1请1显(请求数据处理既提示)
一、创建魔板
命令行:
- 1 创建项目
django-admin startproject cookie_test
- 2 创建后台APP
python manage.py startapp App
- 3 创建对应数据库
create database cookie_test;
修改文件
- 1 创建文件夹cookie_test/template/ cookie_test/static/
- 2 修改配置文件 settings.py
INSTALLED_APPS = (App,) 刚创建的后台APP
‘django.middleware.csrf.CsrfViewMiddleware’, # 需要被注释
添加 TEMPLATES{
‘DIRS’: [
os.path.join(BASE_DIR, “template”.replace(“\“,’/’)),
os.path.join(BASE_DIR, “App”.replace(“\“,’/’)),
],}
数据库
DATABASES = {
‘default’: {
# ‘ENGINE’: ‘django.db.backends.sqlite3’,
# ‘NAME’: os.path.join(BASE_DIR, ‘db.sqlite3’),
‘ENGINE’: ‘django.db.backends.mysql’,
‘NAME’ : “cookie_test”,
‘USER’ : ‘root’,
‘PASSWORD’:‘zjq’,
‘HOST’ :‘localhost’,
‘POST’ :3306,
}
}
中文
LANGUAGE_CODE = ‘en-us’改’zh-hans’ # 汉字
静态路径
STATIC_URL = ‘/static/’
STATICFILES_DIRS = (
os.path.join(BASE_DIR, “static”.replace(“\“, “/”)),
) - 3 修改views.py与urls.py,创建对应HTML,浏览器请求确定魔板魔板没有问题\
- 4 在models里面建立表Student, 将来在数据库中呈现的就是cookie_test/App_Student
- 5 将表在admin中注册 admin.site.register(Student) # 安装表,admin请求时会显示该表
- 6 更新数据库连接
python manage.py validate
python manage.py makemigrations
python manage.py syncdb
- 7 查看数据库 出现cookie_test/App_Student
二、上传数据
<body>
<form action="" method="POST">
<input type="text" name="user">
<input type="password" name="password">
<input type="text" name="phone">
<input type="submit" value="确认">
</form>
<body>
def first_test(request):
register = Register()
if request.method == "POST" and request.POST:
# 传递参数
user = request.POST["user"]
password = request.POST["password"]
phone = request.POST["phone"]
# 密码加密
hash = hashlib.md5()
hash.update(password.encode("UTF-8"))
password = hash.hexdigest()
# 上传数据库
u = Student()
u.name = user
u.password = password
u.phone = phone
u.save()
return render_to_response("first_test.html", locals())
三、创建数据上传完成提示, 使用form魔板
1. 新建forms.py
from django import forms
# 生成forms表单
class Register(forms.Form):
user = forms.CharField(max_length=32, label="用户名") # 默认显示user, 添加label显示label名
password = forms.CharField(max_length=32)
phone = forms.CharField(max_length=15)
def clean_password(self): # 函数明命名必须clean_字段名称
password = self.cleaned_data["password"] # 获取要判断的数据
if password[0].isdigit(): # 判断数字
raise forms.ValidationError("firs cann't be number")
return password
2.HTML调用forms.py
注意将/static/js/jquery.1.11.3.min.js,随便找个网站, 下载一个就行
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>first_test</title>
<script src="/static/js/jquery.1.11.3.min.js"> </script>
</head>
<body>
<!-- <form action="" method="POST"> <input type="text" name="user"> <input type="password" name="password"> <input type="text" name="phone"> <input type="submit" value="确认"> </form> -->
<form action="" method="POST">
{
{register}}
<button onclick="jqAjax()">click</button>
</form>
<script> function jqAjax(){ var json_data = JSON.toString({ "for":"hello"}) $.ajax( { url:"http://127.0.0.1:8000/post_data/", //请求数据为son_data type:"POST", data:json_data, beforeSend:function(){ }, success:function(data){ if(data["statue"]=="success"){ alert("提交成功") } else{ alert("失败") } }, error:function(err){ alert(err) } } ) } </script>
</body>
</html>
3. views.py
from django.shortcuts import render_to_response
from App.models import *
import hashlib
from App.forms import *
from django.http import JsonResponse
# Create your views here.
def first_test(request):
register = Register()
if request.method == "POST" and request.POST:
# 传递参数
user = request.POST["user"]
password = request.POST["password"]
phone = request.POST["phone"]
# 密码加密
hash = hashlib.md5()
hash.update(password.encode("UTF-8"))
password = hash.hexdigest()
# 上传数据库
u = Student()
u.name = user
u.password = password
u.phone = phone
u.save()
return render_to_response("first_test.html", locals())
def post_data(request):
if request.method == "POST" and request.POST:
response_data = { "statue": "success"}
else:
response_data = { "statue": "error"}
return JsonResponse(response_data)
4 urls.py请求与反馈
from django.conf.urls import include, url
from django.contrib import admin
from App.views import *
urlpatterns = [
url(r'^admin', include(admin.site.urls)),
url(r'^first_test/$', first_test),
url(r'^post_data/$', post_data),
]
四、cookie
cookie标识为当前用户存到的本地的验证信息, 如访问京东,第一次登陆之后,后期登陆无需在重新输入账号密码,因为cookie标识在本地, 当再次访问京东网址时, cookie会告诉京东刚用户登陆无需在登陆的一个flag
1 test_cookie.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test_cookie</title>
</head>
<body>
<form>
</form>
</body>
</html>
2 views.py 设置cookie
def test_cookie(request):
response = render_to_response('test_cookie.html', locals())
response.set_cookie("name", "for", 3600) # 在本地存放name for 为3600秒, 在这个时间内,都是以这个for用户来访问的
return response
3 urls.py调用
url(r'^test_cookie/$', test_cookie),
4 结果
在访问同一网站
还没有评论,来说两句吧...