from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
email = forms.EmailField(required=False)
message = forms.CharField()
主要是继承forms.Form ,写法跟models 里面的差不多。
完了之后你可以构造出一个实例。
f = ContactForm()
form类有很多实用的方法,比如说
form api详细可见官网 :
https://docs.djangoproject.com/en/1.8/ref/forms/api/
步骤是
def contact(request):
if request.method == ‘POST‘:
form = ContactForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail(
cd[‘subject‘],
cd[‘message‘],
cd.get(‘email‘, ‘noreply@example.com‘),
[‘siteowner@example.com‘],
)
return HttpResponseRedirect(‘/contact/thanks/‘)
else:
form = ContactForm()
return render(request,‘contact_form.html‘, {‘form‘: form})
如果是get请求,则重新创建一个form对象,然后渲染。
<html>
<head>
<title>Contact us</title>
</head>
<body>
<h1>Contact us</h1>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<form action="" method="post">
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
</body>
</html>
这里调用了form.as_table生成 表格形式的表单,默认他是全部在一行上面的。
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/aca_jingru/article/details/47975475