One: Implementing forms using the Forms class
1: We generally put form < Span class= "Pre" style= "Font-weight:800;font-size:12px;font-family:consolas, ' Courier New ';" >forms.py Can be stored in the app's directory, such as my app for the books directory.
Add in forms.py:
From Django Import Formsclass contactform (forms. Form): Subject = forms. Charfield () email = forms. Emailfield (required=false) message = forms. Charfield ()
each field is required by default. To makeEmailas an option, we need to specifyRequired=false.
2: Invoke forms in view, add in views
from django.shortcuts import render_to_responsefrom mysite.contact.forms import Contactformdef 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] '), &nbSp; [' [email protected] '], ) return Httpresponseredirect ('/contact/thanks/') else: form = contactform () #必须加最后一句否则或出错return render_to_response ( ' contact/contact_form.html ', {' form ': form},context_instance=requestcontext (Request))
3: We create a new form directory and form file in templates, directory location/templates/contact/contact_form.html
Contact_form.html
4: Add the view path to the URL to access the
This article is from the "Django Advanced Programming" blog, reproduced please contact the author!
Django under Simple form validation implementation on