6(just form no database)
2015-11-12 本文已影响0人
EudeMo
添加一个不需要写入数据库的表单contact
- 在forms.py中添加contact类
class ContactForm(forms.Form):
name = forms.CharField(max_length=120)
email = forms.EmailField()
phonenumber = forms.CharField(max_length=20)
def clean_email(self):
email = self.cleaned_data.get('email')
email_base, email_provider = email.split("@")
email_domain, email_extension = email_provider.split('.')
print(email_base, email_provider, email_domain, email_extension)
if not email_domain == '163':
raise forms.ValidationError("you should input 163 email")
return email #实际上被写入的email的值
- 在views.py里添加如下代码:
def contact(request):
form = ContactForm(request.POST or None)
title = "hi contact"
if form.is_valid():
for key,value in form.cleaned_data.items():#python2.7使用iteritems()
print(key,value)
context = {
'form':form,
'title':title,
}
return render(request, 'contact.html', context)
- 在templates文件夹下面添加contract.html文件
<h1>{{ title }}</h1>
<form method="POST" action=""> {% csrf_token %}
{{ form.as_p }}<!-- as_p的作用是让他按行显示,而不是显示在一行 -->
<input type="submit" value="submit">
</form>