CE419 Session 17: Forms Web Programming Forms <form> is the - - PowerPoint PPT Presentation
CE419 Session 17: Forms Web Programming Forms <form> is the - - PowerPoint PPT Presentation
CE419 Session 17: Forms Web Programming Forms <form> is the way that allows users to send data to server for processing. 2 Forms 3 Processing Forms Its possible to process forms just using Djangos HttpRequest class.
Forms
- <form> is the way that allows users to send data to
server for processing.
2
Forms
3
Processing Forms
- It’s possible to process forms just using Django’s
HttpRequest class.
- request.GET, request.POST, request.FILES
- Ain't Nobody Got Time For That!
4
Processing Forms – The Stone Age Way
def register(request): if request.method == "POST": username = request.POST.get('username', None) if not username: username_error = u"ﺪﯿﻵﻨﮐ دﺪرﺮاﺎوﻮ اﺎرﺮ یﯽﺮﺑرﺮﺎﮐ مﻢﺎﻧ." elif not re.match("[\d\w_\.]{3,}", username): username_error = u"ﻞﻣﺎﺷ وﻮ ﺮﺘﮐاﺎرﺮﺎﮐ ﮫﻫﺳ ﻞﻗاﺎﺪﺣ ﺪﯾﻴﺎﺑ یﯽﺮﺑرﺮﺎﮐ مﻢﺎﻧ ﺪﺷﺎﺑ فﻒوﻮﺮﺣ وﻮ دﺪاﺎﺪﻋاﺎ." elif User.objects.filter(username=username).count() > 0: username_error = u"ﺖﺳاﺎ هﻪﺪﺷ ﮫﻫﺘﻓﺮﮔ ﻼﺒﻗ یﯽﺮﺑرﺮﺎﮐ مﻢﺎﻧ ﻦﯾﻴاﺎ." email = request.POST.get('email', None) if not email: email_error = u"ﺪﯿﻵﻨﮐ دﺪرﺮاﺎوﻮ اﺎرﺮ ﻞﯿﻵﻤﯾﻴاﺎ سﺲرﺮدﺪآﺂ." elif not email_re.search(email): email_error = u"ﺪﯿﻵﻨﮐ دﺪرﺮاﺎوﻮ اﺎرﺮ یﯽﺮﺒﺘﻌﻣ ﻞﯿﻵﻤﯾﻴاﺎ." elif User.objects.filter(email=email).count() > 0: email_error = u"ﺖﺳاﺎ هﻪﺪﺷ هﻪدﺪﺎﻔﺘﺳاﺎ ﻼﺒﻗ ﻞﯿﻵﻤﯾﻴاﺎ سﺲرﺮدﺪآﺂ ﻦﯾﻴاﺎ."
5
Default value in the case that ‘username’ doesn’t exist.
Processing Forms – The Stone Age Way
- Pretty cool, huh?
- Don’t Repeat Yourself, dude.
6
Django Forms API
- Helps you with some common tasks:
- Auto-generate an HTML form for you,
- Check submitted data against set of validation rules,
- Redisplay form in case of errors,
- Convert submitted data to relevant Python types.
7
Form Object
- A Form object encapsulates a sequence of form fields
and a collection of validation rules.
from django import forms class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() cc_myself = forms.BooleanField(required=False)
CharField DateField FileField EmailField BooleanField RegexField … forms.py
9
Field Object
- Important field arguments:
- Field.required
- Field.label
- Field.initial
- Field.widget
- Field.help_text
- Field.error_messages
- Field.validators
father_name = forms.CharField(required=False) url = forms.URLField(label='Your Web site') url = forms.URLField(initial='http://') comment = forms.CharField(widget=forms.Textarea)
Not for fallback.
sender = forms.EmailField(help_text='Real address.') name = forms.CharField(error_messages={'required': ‘Enter your name, dude.’}) even_field = forms.IntegerField(validators=[validate_even])
10
Using a Form in a View
from django.shortcuts import render from django.http import HttpResponseRedirect from mysite.forms import ContactForm def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # processing the form and doing something return HttpResponseRedirect('/thanks/') else: form = ContactForm() return render(request, 'contact.html', {'form': form,})
There are three different code paths here.
Bound vs. Unbound
The successfully validated form data will be in the form.cleaned_data dictionary.
11
Processing the Form
if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] sender = form.cleaned_data['sender'] cc_myself = form.cleaned_data['cc_myself'] recipients = ['info@example.com'] if cc_myself: recipients.append(sender) from django.core.mail import send_mail send_mail(subject, message, sender, recipients) return HttpResponseRedirect('/thanks/')
You can still access the unvalidated data directly from request.POST.
12
Displaying the Form
<form action="/contact/" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form>
Don’t panic. We’ll talk about this in a later session. Only outputs form fields, don’t forget <form></form>.
Render result: <form action="/contact/" method="post"> <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p> <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p> <p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></p> <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p> <input type="submit" value="Submit" /> </form>
13
Don’t Like It? Okay, whatever.
<form action="/contact/" method="post"> {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.subject.errors }} <label for="id_subject">Email subject:</label> {{ form.subject }} </div> <div class="fieldWrapper"> {{ form.message.errors }} <label for="id_message">Your message:</label> {{ form.message }} </div> <div class="fieldWrapper"> {{ form.sender.errors }} <label for="id_sender">Your email address:</label> {{ form.sender }} </div> <div class="fieldWrapper"> {{ form.cc_myself.errors }} <label for="id_cc_myself">CC yourself?</label> {{ form.cc_myself }} </div> <p><input type="submit" value="Send message" /></p> </form> Displays a list of form errors, rendered as an unordered list. Produces the HTML needed to display the form widget.
14
We’ll talk about it in a minute. Be patience.
More Convenient Way
<form action="/contact/" method="post"> {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} {{ field }} </div> {% endfor %} <p><input type="submit" value="Send message" /></p> </form>
{{ field.label }} {{ field.value }} {{ field.help_text }} {{ field.is_hidden }} {{ field.field }} {{ field.html_name }} ...
15
Using Forms Directly with a Model
- Don’t Repeat Yourself
class Author(models.Model): name = models.CharField(max_length=100) title = models.CharField(max_length=3, choices=TITLE_CHOICES) birth_date = models.DateField(blank=True, null=True) def __str__(self): return self.name class Book(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Author) class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ['name', 'title', 'birth_date'] class BookForm(forms.ModelForm): class Meta: model = Book fields = ['name', 'authors']
ModelForm objects have an extra .save() method.
16
Any Questions?
26
References
- https://docs.djangoproject.com/en/1.6/topics/forms/
- https://docs.djangoproject.com/en/1.6/ref/forms/fields/
- https://docs.djangoproject.com/en/1.6/ref/forms/
widgets/
- https://docs.djangoproject.com/en/1.6/ref/forms/
validation/
- http://www.python.org
27