10.2. Forms Form
from django import forms
from django.views.generic import FormView, TemplateView
class ContactForm(forms.Form):
sender = forms.EmailField(label='Your Email Address')
category = forms.ChoiceField(choices=[('question', 'Question'), ('other', 'Other')])
subject = forms.CharField(required=False)
body = forms.CharField(widget=forms.Textarea)
class ContactView(FormView):
template_name = 'shop/contact-form.html'
form_class = ContactUsForm
success_url = '/shop/contact/thankyou'
class ThankYouView(TemplateView):
template_name = 'shop/contact-thankyou.html'
- forms.py:
from django import forms class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField(widget=forms.Textarea) sender = forms.EmailField() cc_myself = forms.BooleanField(required=False) def clean_sender(self): data = self.cleaned_data['sender'] if "mark.watney@nasa.gov" not in data: raise forms.ValidationError("You have forgotten about Watney!") # Always return a value to use as the new cleaned data, even if # this method didn't change it. return data
- views.py:
from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import NameForm def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: form = NameForm() return render(request, 'name.html', {'form': form})
- form.html:
<form action="/your-name/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form>
{{ form.as_table }}
will render them as table cells wrapped in<tr>
tags{{ form.as_p }}
will render them wrapped in<p>
tags{{ form.as_ul }}
will render them wrapped in<li>
tags