# -*-coding:utf-8-*-
from django import formsclass ContactForm(forms.Form): subject = forms.CharField(max_length=100) email = forms.EmailField(required=False, label='Your e‐mail address') """ forms框架把每一个字段的显示逻辑分离到一组部件(widget)中。 每一个字段类型都拥有一个默认的部件, 我们也可以容易地替换掉默认的部件,或者提供一个自定义的部件 """ message = forms.CharField(widget=forms.Textarea) """ Django的form系统自动寻找匹配的函数方法,该方法名称以clean_开头,并以字段名称结束。 如果有这样的 方法,它将在校验时被调用 """ def clean_message(self): message = self.cleaned_data['message'] num_words = len(message.split()) if num_words < 4: raise forms.ValidationError("Not enough words!") return message
# -*-coding:utf-8-*-from django.core.mail import send_mailfrom django.http import HttpResponseRedirectfrom django.shortcuts import render_to_responsefrom contact.forms import ContactFormdef contact(request): errors = [] if request.method == 'POST': if not request.POST.get('subject'): errors.append('Enter a subject.') if not request.POST.get('message'): errors.append('Enter a message.') if request.POST.get('email') and '@' not in request.POST['email']: errors.append('Enter a valid e‐mail address.') if not errors: send_mail( request.POST['subject'], request.POST['message'], request.POST.get('email', 'noreply@example.com'), ['siteowner@example.com'], ) return HttpResponseRedirect('/contact/thanks/') return render_to_response('contact_form.html',{ 'errors': errors})def contact2(request): if 'POST' == request.method: form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data send_mail(cd['subject'], cd['message'], cd.get('email','noreply@example.com'), []) return HttpResponseRedirect('/contact/thanks/') else: """ 传入初始值数据和传入数据以绑定表单是有区别的。 最大的区别是,如果仅传入* 初始值* 数 据,表单是unbound的,那意味着它没有错误消息。 """ form = ContactForm(initial={ 'subject': 'I love your site!'}) return render_to_response('contact_form.html', { 'form': form})
Contact us {% if form.errors %}Please correct the error{
{ form.errors|pluralize }} below. {% endif %}
Contact us Contact us
{% if form.errors %}Please correct the error{
{ form.errors|pluralize }} below. {% endif %}