一分钟学会Django的表单
#forms.pyfrom django import forms
class ContactForm(forms.Form):
subject = forms.CharField()
email = forms.EmailField(required=False, label='Your e-mail address') #define label
message = forms.CharField(widget=forms.Textarea ) #define output format
#define custom check method, nameing rule clean_attname(), executed after default clean(),e.g, is_valid() method.
#we can set cleand_data to the python value we want, so the value is better returned or we will lost the value.
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
[python] view plaincopy
# views.py
from django.shortcuts import render_to_response
from mysite.contact.forms import ContactForm
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid(): #if valid, then cleaned_data attr is gen.
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() #or add an initial value
form = ContactForm(initial={'subject': 'I love your site!'})
return render_to_response('contact_form.html', {'form': form})
# contact_form.html
<html>
<head>
<title>Contact us</title>
<style type="text/css">
ul.errorlist {
margin: 0;
padding: 0;}
.errorlist li {
background-color: red;
color: white;
display: block;
font-size: 10px;
margin: 0 0 3px;
padding: 4px 5px;}
</style>
</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">
<div class="field"> #define you own style
{{ form.subject.errors }}
<label for="id_subject">Subject:</label>
{{ form.subject }}
</div>
<div class="field">
补充:Web开发 , Python ,