python-web应用程序-Django-From组件
添加用户时
原始方法(本质)【麻烦】
python
def user_add(req):
if req.method == 'GET':
return render(req,'XXX.html')
#POST请求处理:
XXXXX
-用户数据没有校验
-出现错误提示
-页面上的每一个字段都需要我们重新写一遍
-关联数据需要手动获取
Django组件
Form组件(方便)
python
class MyForm(Form):
user = forms.CharField(widget = forms.Input)
pwd = forms.CharField(widget = forms.Input)
email = forms.CharField(widget = forms.Input)
XXX=XXX
---
def user_add(req):
if req.method == 'GET':
form = MyForm()
return render(req,'XXX.html',{'form':form})
#POST请求处理:
XXXXX
2.user_add.html
html
<form method="post">
{{ form.user }}
{{ form.pwd }}
{{ form.email }}
<!-- 自动生成:<input type="text"placeholder="姓名" name="user"/> -->
或者:
{% for field in form %}
{{field.lable}} : {{field}}
{% endfor %}
</form>
ModelForm组件(更方便)
在modelForm中不需要手动写类的声明
python
class MyForm(ModelForm):
xx = form.CharField(XXXX) #新增加的字段
class Meta:
model = model.类
fields = ['name','password','---']
其余与Form相同
- 当传的对象为【对象,对象,对象,】时需要写该类的__str__方法
python
class depart(models.Model):
title = models.CharField(max_length=10)
def __str__(self):
return self.title
#定制返回值
给自动生成的输入框增加样式
view.py中:
python
class UserInfo(forms.ModelForm):
class Meta:
model = models.UserInfo
fields = ['name','password','ahe']
widgets = {
'name':forms.TextInput(attrs={'class':'layui-input'})
'password':forms.TextInput(attrs={'class':'BootStrip-form-control'})
'XXXX':XXXX
}
python
#自动添加样式
class UserInfo(forms.ModelForm):
class Meta:
model = models.UserInfo
fields = ['name','password','ahe']
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
for name,field in self.fields.items():
if name =='':
XXXXX#单独处理or continue不处理
field.widget.attrs= {'class':'XXXXX','placehoder':field.label}
校验
python
def user_add(req):
if req.method == 'GET':
form = UserInfo()
return render(req,'XXX.html',{'form':form})
#POST请求处理:
form = UserInfo(data = req.POST)
if form.is_valid():
print(form.cleaned_data)
else:
print(form.errors)
#{'name':'yulin','password':'123456'...}
#models.UserInfo.object.create(XXXX)
form.save()
return redirect('/user/list/')
#检验失败
return render(req,'user_add.html',{'form',form})
#该form中存在错误信息
html
#前端获取错误信息
{% for field in form %}
<div class="form-group">
<label>{{ field.Label }}</label>
{{ field }}
<span styLe="coLor: red;">{{ field.errors.0 }} </span>
</div>
{% endfor %}