##### 在写django的时候之前一直没有理解django表单所带来的便利,好不容易明白了,就想写点自己的笔记,记录总结一下django表单的用法。
首先看看views.py中的代码
from django import forms
from django.forms import fields
from django.forms import widgets
#生成一个form表单的类,字段为我们要填写的字段,
#error_messsages为字段验证不通过时的报错
#widgets可以为所要填写字段的类型,以及添加html的属性
class UserForm(forms.Form):
username = fields.CharField(required=True,
error_messages={'required':"用户名不为空"},
widget=widgets.TextInput(attrs={'class':'form-control'}))
password = fields.CharField(required=True,
error_messages={'required': "密码不为空"},
widget=widgets.TextInput(attrs={'class': 'form-control'}))
email = fields.EmailField(required=True,
error_messages={'required': "邮箱不为空","invalid":"邮箱格式错误"},
widget=widgets.EmailInput(attrs={'class': 'form-control'}))
ut_id =fields.IntegerField(required=True,
widget=widgets.Select(attrs={'class':'form-control'},
choices=models.UserType.objects.values_list('id','name')))
#这里根据UserType已经添加的类型进行选择用户类型
#这里执行了构造方法是,如果我们添加了新的用户类型的话,除非重启服务,否则不会加载新的数据,所以要添加一个构造方法
#来进行重新加载
def __init__(self,*args,**kwargs):
super(UserForm,self).__init__(*args,**kwargs)
self.fields['ut_id'].widget.choices = models.UserType.objects.values_list('id','name')
#判断request.method的方法,是则创建实例,obj,然后传给模板进行渲染
#如果是别的请求则接受POST请求的数据,传给UserForm类,然后执行实例的方法is_valid()来判断符合,
#我们之前要求的数据格式不,验证通过的数据直接传给models来进行创建
def add_user(request):
if request.method == "GET":
obj = UserForm()
return render(request,'add_user.html',{'obj':obj})
else:
obj =UserForm(request.POST)
if obj.is_valid():
print ("pass",obj.cleaned_data)
models.UserInfo.objects.create(**obj.cleaned_data)
return redirect('/users2')
else:
pass
return render(request, 'add_user.html',{'obj':obj})
#这里是编辑的视图,先进行表单的初始化initial来进行初始化
def edit_user(request,uid):
if request.method == "GET":
user = models.UserInfo.objects.filter(id=uid).first()
obj = UserForm(initial={'username':user.username,'password':user.password,'email':user.email,'ut_id':user.ut_id})
return render(request,'edit_user.html',{'uid':uid,'obj':obj})
else:
obj = UserForm(data = request.POST)
if obj.is_valid():
models.UserInfo.objects.filter(id=uid).update(**obj.cleaned_data)#使用update方法来进行更新
return redirect('/users2')
return render(request,'edit_user.html',{'uid':uid,'obj':obj})
下面是模板的代码,创建用户的表单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css"/>
</head>
<body>
<div style="width: 600px;margin: 0 auto;">
<form method="POST" action="/add-user">
{% csrf_token %}
<div class="form-group">
<label>用户名</label>
{{obj.username}} #这里传来的表单对象
<span>{{ obj.errors.username.0 }}</span> #这里是报错的信息
</div>
<div class="form-group">
<label >密码</label>
{{obj.password}}
<span>{{ obj.errors.password.0 }}</span>
</div>
<div class="form-group">
<label >邮箱</label>
{{obj.email}}
<span>{{ obj.errors.email.0 }}</span>
</div>
<div class="form-group">
<label >用户类型</label>
{{obj.ut_id}}
<span>{{ obj.errors.ut_id.0 }}</span>
</div>
<button type="submit" class="btn btn-default">提交</button>
</form>
</div>
</body>
</html>
下面这个是编辑用户的表单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css"/>
</head>
<body>
<div style="width: 600px;margin: 0 auto;">
<form method="POST" action="/edit-user-{{uid}}"> #这里会获取UID的信息,urls.py中是这样
{% csrf_token %} # url(r'^edit-user-(\d+)$', views.edit_user),
<div class="form-group">
<label>用户名</label> #其他的同创建表单一样
{{obj.username}}
<span>{{ obj.errors.username.0 }}</span>
</div>
<div class="form-group">
<label >密码</label>
{{obj.password}}
<span>{{ obj.errors.password.0 }}</span>
</div>
<div class="form-group">
<label >邮箱</label>
{{obj.email}}
<span>{{ obj.errors.email.0 }}</span>
</div>
<div class="form-group">
<label >用户类型</label>
{{obj.ut_id}}
<span>{{ obj.errors.ut_id.0 }}</span>
</div>
<button type="submit" class="btn btn-default">提交</button>
</form>
</div>
</body>
</html>
最后对于上传文件的总结
def test(request):
if request.method == "GET":
obj = TestForm()
return render(request,"test.html",{'obj':obj})
else:
# obj = TestForm(request.POST,files=request.FILES)
# if obj.is_valid(): #老式的上传文件,先写入内存,然后写
# file_obj = obj.cleaned_data['n5'] #写到指定的目录
# file_obj.name
# f = open(file_obj.name,'wb')
# for chunk in file_obj.chunks():
# f.write(chunk)
# f.close()
# else:
# pass
import os
file_obj = request.FILES.get('n5') #这里是新的方法
f = open(os.path.join('static',file_obj.name), 'wb')
for chunk in file_obj.chunks():
f.write(chunk)
f.close()
return redirect('/test')
class TestForm(forms.Form): #表单
n5 = fields.FileField()