django第四天
1、form组件
解决两个事情:
- 不想重复提交,数据重置;
- 校验规则
流程:
(1) 创建form组件对应的类,比如LoginForm
(2)
views.login:
if get请求:
form_obj=LoginForm()
return render(request,"login.html",{"form_obj":form_obj}) # 由form_obj渲染form表单的有效控件
渲染方式三种:
1
<form action="" novalidate method="post">
{% csrf_token %}
{{ form_obj.as_p }}
<input type="submit">
</form>
2
<form action="" novalidate method="post">
{% csrf_token %}
<div>
<label for="">用户名</label>
{{ form_obj.user }} <span>{{ form_obj.errors.user.0 }}</span>
</div>
<div>
<label for="">密码</label>
{{ form_obj.pwd }}<span>{{ form_obj.errors.pwd.0 }}</span>
</div>
<input type="submit">
</form>
3
<form action="" novalidate method="post">
{% csrf_token %}
{% for field in form_obj %}
<div>
<label for="">{{ field.label }}</label>
{{ field }}
</div>
{% endfor %}
<input type="submit">
</form>
if post请求:
form_obj = LoginFrom(request.POST)
if form_obj.is_valid():
form_obj.cleaned_data # 所有的有效数据
else:
#form_obj.errors # {}
#form_obj.errors.get("user") # []
return render(request, "login.html", {"form_obj": form_obj})
urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^register/', views.register),
]
models.py
from django.db import models
# Create your models here.
class UserInfo(models.Model):
name = models.CharField(max_length=32)
pwd = models.CharField(max_length=32,default=1)
views.py
from django.shortcuts import render, HttpResponse
from .models import *
# Create your views here.
from django import forms
from django.forms import widgets
from django.core.exceptions import ValidationError
class RegForm(forms.Form):
name = forms.CharField(
label='用户名',
max_length=16,
min_length=3,
error_messages={
"required": "不能为空",
"invalid": "格式错误",
"min_length": "用户名最短3位",
"max_length": "用户名最长16位"
}
)
pwd = forms.CharField(
error_messages={
"required": "不能为空",
},
widget=widgets.PasswordInput(attrs={})
)
repeat_pwd = forms.CharField(
error_messages={
"required": "不能为空",
},
widget=widgets.PasswordInput(attrs={})
)
email = forms.EmailField()
phone = forms.CharField()
def clean_user(self):
val = self.cleaned_data.get('user') # 注意是cleaned_data
ret = UserInfo.objects.filter(name=val)
if not ret:
return val # 通过,返回该值,不通过,返回错误信息,ValidationError()
else:
raise ValidationError('该用户已注册')
def clean_phone(self):
val = self.cleaned_data.get('phone')
import re
ret = re.search("^1[3578]d{9}$", val)
if ret:
return val
else:
raise ValidationError('手机号格式错误')
def clean(self): # clean是全局钩子
pwd = self.cleaned_data.get('pwd')
repeat_pwd = self.cleaned_data.get('repeat_pwd')
if pwd == repeat_pwd:
return self.cleaned_data
else:
raise ValidationError('两次密码不一致')
def register(request):
if request.method == 'POST':
reg_form = RegForm(request.POST)
if reg_form.is_valid():
name = reg_form.cleaned_data.get('name')
pwd = reg_form.cleaned_data.get('pwd')
UserInfo.objects.create(name=name, pwd=pwd)
return HttpResponse('注册成功!')
else:
all_err = reg_form.errors.get('__all__')
print(all_err)
return render(request, 'register.html', locals())
reg_form = RegForm()
return render(request, 'register.html', locals()) # 包含函数执行,到这locals的所有局部变量。
templates
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>注册页面</h1>
<form action="" method="post" novalidate>
{% csrf_token %}
{% for field in reg_form %}
<div>
<label for=""> {{ field.label }}</label>
{{ field }} <span>{{ field.errors.0 }}</span>
{% if field.label == 'Repeat pwd' %}
<span>{{ all_err.0 }}</span>
{% endif %}
</div>
{% endfor %}
<button type="submit">提交</button>
</form>
</body>
</html>
2、用户认证auth模块
request.user 存的是当前用户的对象,没有登录的话是一个匿名用户对象。
1 使用auth_user表作为用户表
2 登录:
user=auth.authenticate(username=user,password=pwd)
auth.login(request,user) # session写操作
auth.logout(request) # request.session.flush()
验证 user.is_authenticated() # 登录状态时,返回True,否则返回False
创建用户:User.objects.create_user(username="egon123",password="1234")
3、 ajax
locals() 深拷贝 完全独立,模板里改变变量的值,函数里的值不会改变。
ajax
https://www.cnblogs.com/maple-shaw/articles/9524153.html
1. 发请求的途径
1. 在浏览器地址上输入地址 回车 ——》 GET
2. form表单 ——》 GET / POST
3. a标签 ——》 GET
2. ajax
使用js技术发送异步请求 一般传输json数据
特点:
局部刷新 当前页面不刷新
异步
1. 计算示例
$.ajax({
url:'/calc1/',
type:'post',
data:{
i1:$('[name="ii1"]').val(),
i2:$('[name="ii2"]').val()
},
success:function (res) {
console.log(res);
$('[name="ii3"]').val(res)
}
})
2. ajax的参数介绍
上传文件
form_obj = new FormData();
form_obj.append('f1', $('#f1')[0].files[0]);
# jquery对象转换为dom对象,方法files,可能传多个文件,只要一个,【0】,这就包含了数据得form_data对象。
$.ajax({
url: '/upload/',
type: 'post',
processData: false,
# 告诉ajax不处理编码方式,enctype=form——data,这个form——obj本身就是这个编码方式,但是django会默认帮你改成urlencode得方式,告诉django不用改
contentType: false, # 告诉ajax不处理contentType,数据类型,不改请求头
data: form_obj,
success: function (res) {
console.log(res); # 返回的响应的响应体
},
})
2.
headers:{'X-csrftoken':$('[name="csrfmiddlewaretoken"]').val()},
3、 使用文件