一:使用forms类实现表单
1:我们一般把Form类都放到一个文件中:forms.py。具体可存放`在APP的目录,如我的APP为BOOKS目录中。
在forms.py里添加:
from django import forms class ContactForm(forms.Form): subject = forms.CharField() email = forms.EmailField(required=False) message = forms.CharField()
每一个字段都默认是必填。要使email成为可选项,我们需要指定required=False。
2:在视图里调用forms,在views里添加
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(): cd = form.cleaned_data send_mail( cd[‘subject‘], cd[‘message‘], cd.get(‘email‘, ‘[email protected]‘), [‘[email protected]‘], ) return HttpResponseRedirect(‘/contact/thanks/‘) else: form = ContactForm() #必须加最后一句否则或出错return render_to_response(‘contact/contact_form.html‘, {‘form‘: form},context_instance=RequestContext(request))
3:我们在templates里新建表单目录和表单文件,目录位置/templates/contact/contact_form.html
contact_form.html
<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"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> </form> </body> </html>
4:在url里添加view路径,就可以访问了
时间: 2024-10-19 21:29:03