Setting Initial Values
As an improvement to this form, let’s add an initial value for the subject field: "I love your site!" (A little power of suggestion can’t hurt.) To do this, we can use the initial argument when we create a Form instance:
(设置初始值书中的程序有点小错误,中英文都有)
中文版的程序如下:
英文版程序如下:
正确的程序如下:
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(
initial={'subject': 'I love your site!'}
)
return render_to_response('contact_form.html', {'form': form})
PS:此处的错误时书中常见的两个错误,在中文版中python代码里经常会多出几个**号,英文版的render应该为render_to_response。此外,此处的中文版程序邮件格式里面还有奇怪的符号,删除了就好了。