http://www.yihaomen.com/article/python/232.htm
在用django 时,处理表单的时候,经常使用传统的方式,在 html 页面中自己去写各种field ,然后再后面 request.POST.get() 方式去得到处理。但事实上 django 给我们提供了 内嵌的 form 去处理,看了下django的资料,今天单独列出一个工程来来测试。
Django Form 主要有两种处理方式:
1.直接继承 forms.Form
2.直接利用已有的model中的class,从ModelForm中继承.
这两种方式,都涉及到如下几个问题:
1.django form 显示中文字段名
2.django form field 的样式控制
3.django form 的数据校验
4.django form 数据提交后的处理.
整个工程结构如下:
直接继承于forms.form 的情况下:
![程序代码](http://www.yihaomen.com/images/code.gif)
class TestForm(forms.Form):
#==label 用来控制 form 字段的 中文显示,widget 可以控制其他属性,比如样式等。
yourname = forms.CharField(label='名称',max_length=50,widget=forms.TextInput(attrs={'style':'border:1px solid #ccc;'}))
website = forms.URLField(required=False,widget=forms.TextInput(attrs={'class':'myclass'}))
email = forms.EmailField(label='邮箱')
content = forms.CharField(label='内容',widget=forms.Textarea(attrs={'cols':'80','rows':'5'}))
def add_comment(request):
context={}
context.update(csrf(request))
form = TestForm()
context['form']=form
return render_to_response('form.html',context)
def save_comment(request):
form = TestForm(request.POST)
#===校验form 中的数据,并处理.
if form.is_valid() :
print 'successs'
yourname = form.cleaned_data['yourname']
website = form.cleaned_data['website']
email = form.cleaned_data['email']
content = form.cleaned_data['content']
#===想干嘛就干嘛,可以插入数据库等
print 'get information:',yourname,email,website,content
return render_to_response('form.html',locals())
else:
print 'error'
return render_to_response('form.html',locals())
form.html 模板如下:
![程序代码](http://www.yihaomen.com/images/code.gif)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" " http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Add contact</title>
</head>
<body>
<div><h2> 直接forms.Form 方式 </h2></div>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<form method="POST" action="/save_contact/">
{% csrf_token %}
<table>
{{form.as_table}}
</table>
<input type="submit" value="submit"/>
</form>
</body>
</html>
如果用ModelForm 实现
必须先在models.py 中定义 class
![程序代码](http://www.yihaomen.com/images/code.gif)
class MyComment(models.Model):
#===显示的中文名称,可以直接在这里定义,也可以在 views.py 中相应方法处理.
yourname = models.CharField('名称',max_length=50)
website = models.URLField()
email = models.EmailField()
content = models.TextField('内容')
qq = models.CharField(max_length=20)
msn = models.CharField(max_length=100)
hiddenfields1 = models.CharField(max_length=50)
然后在views.py 中实现。
![程序代码](http://www.yihaomen.com/images/code.gif)
class TestModelForm(ModelForm):
class Meta:
model = MyComment
#==只显示这几个字段================
fields = ('yourname','email','website','content','qq','msn')
#==或者用排除法
#exclude = ('hiddenfields1',)
#===如果需要变更样式, 或者变更显示中文名称.更改 label
def __init__(self, *args, **kwargs):
super(TestModelForm, self).__init__(*args, **kwargs)
#====改变样式,也可以赋值 class=???,在外面html页面上先定义好,个人不推荐直接在代码里写,只是为了演示。
self.fields['yourname'].widget.attrs.update({'style' : 'border:1px dashed #ccc;'})
self.fields['email'].label='伊妹儿'
def add_model_comment(request):
context={}
context.update(csrf(request))
form = TestModelForm()
context['form']=form
return render_to_response('modelform.html',context)
def save_model_comment(request):
form = TestModelForm(request.POST)
if form.is_valid() :
print 'successs'
yourname = form.cleaned_data['yourname']
website = form.cleaned_data['website']
email = form.cleaned_data['email']
content = form.cleaned_data['content']
qq = form.cleaned_data['qq']
msn = form.cleaned_data['msn']
#===想干嘛就干嘛,可以插入数据库等
print 'get information:',yourname,email,website,content,qq,msn
return render_to_response('modelform.html',locals())
else:
print 'error'
return render_to_response('modelform.html',locals())
运行查看效果图:
![](http://www.yihaomen.com/attachments/month_1208/p2012824115041.png)
![](http://www.yihaomen.com/attachments/month_1208/c2012824115054.png)
![](http://www.yihaomen.com/attachments/month_1208/z201282411511.png)
源码下载:
![下载文件](http://www.yihaomen.com/images/download.gif)