Tuesday, July 31, 2012

The Standard Way of using a form in a field (when to call constructors, when to construct bound with arguments, when to redirect)


https://docs.djangoproject.com/en/dev/topics/forms/


Using a form in a view

The standard pattern for processing a form in a view looks like this:
from django.shortcuts import render
from django.http import HttpResponseRedirect

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

    return render(request, 'contact.html', {
        'form': form,
    })



2

Form submitted?Data?What occurs
UnsubmittedNone yetTemplate gets passed unbound instance of ContactForm.
SubmittedInvalid dataTemplate gets passed bound instance of ContactForm.
SubmittedValid dataValid data is processed. Redirect to a "thanks" page.



3

The distinction between Bound and unbound forms is important:
  • An unbound form has no data associated with it. When rendered to the user, it will be empty or will contain default values.
  • A bound form has submitted data, and hence can be used to tell if that data is valid. If an invalid bound form is rendered, it can include inline error messages telling the user what data to correct.








No comments:

Post a Comment