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 • 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 Default value in the case that def register(request): ‘username’ doesn’t exist. 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
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 forms.py 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 … � 9
Field Object • Important field arguments: • Field.required father_name = forms.CharField(required=False) • Field.label url = forms.URLField(label='Your Web site') • Field.initial url = forms.URLField(initial='http://') Not for fallback. • Field.widget comment = forms.CharField(widget=forms.Textarea) • Field.help_text sender = forms.EmailField(help_text='Real address.') • Field.error_messages name = forms.CharField(error_messages={'required': ‘Enter your name, dude.’}) • Field.validators even_field = forms.IntegerField(validators=[validate_even]) � 10
Using a Form in a View There are three different code paths here. from django.shortcuts import render from django.http import HttpResponseRedirect from mysite.forms import ContactForm The successfully validated form data will be in the def contact(request): form.cleaned_data if request.method == 'POST': dictionary. 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,}) Bound vs. Unbound � 11
Processing the Form if form.is_valid(): You can still access subject = form.cleaned_data['subject'] the unvalidated data message = form.cleaned_data['message'] directly from request.POST . 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/') � 12
Displaying the Form Don’t panic. We’ll talk about this in a later session. <form action="/contact/" method="post">{% csrf_token %} Only outputs form {{ form.as_p }} fields, don’t forget <input type="submit" value="Submit" /> <form></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"> We’ll talk about it in a minute. Be {{ form.non_field_errors }} patience. <div class="fieldWrapper"> {{ form.subject.errors }} <label for="id_subject">Email subject:</label> Produces the HTML needed to {{ form.subject }} display the form widget. </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 }} Displays a list of form errors, </div> rendered as an unordered list. <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> � 14
More Convenient Way <form action="/contact/" method="post"> {% for field in form %} {{ field.label }} <div class="fieldWrapper"> {{ field.value }} {{ field.errors }} {{ field.help_text }} {{ field.label_tag }} {{ field }} {{ field.is_hidden }} {{ field.field }} </div> {{ field.html_name }} {% endfor %} ... <p><input type="submit" value="Send message" /></p> </form> � 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'] ModelForm objects have an class BookForm(forms.ModelForm): extra .save() method. class Meta: model = Book fields = ['name', 'authors'] � 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
Recommend
More recommend