Login

FormHandler - take the legwork out of form processing

Author:
zvoase
Posted:
September 22, 2008
Language:
Python
Version:
1.0
Score:
2 (after 2 ratings)

Take the legwork out of processing forms.

Most people have a very specific structure to how they process forms in views. If the request method is "GET", then some HTML (with the blank form) is rendered. If the method is "POST", then the form is validated. If the form is invalid, some other HTML is displayed. If valid, the data is submitted and processed in some way.

In order to do this all in a much nicer way, simply subclass FormHandler, define three methods (valid, invalid and unbound), point to the form, and use the subclass as your view in the URLconf.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from django.http import HttpResponse


class FormHandler(HttpResponse):
    
    def __init__(self, request, *args, **kwargs):
        if request.method == 'POST':
            form = self.form(request.POST)
            if form.is_valid():
                self._update(self.valid(request, form, *args, **kwargs))
            else:
                self._update(self.invalid(request, form, *args, **kwargs))
        else:
            self._update(self.unbound(request, self.form(), *args, **kwargs))
    
    def _update(self, response):
        if not response:
            return
		self._charset = response._charset
		self._is_string = response._is_string
		self._container = response._container
		self._headers.update(response._headers)
		self.cookies.update(response.cookies)
		self.status_code = response.status_code


###########
# EXAMPLE #
###########


class MyFormHandler(FormHandler):
    
    form = MyForm
    
    def valid(self, request, form):
        process_form(form)
        submit(some_data)
        do(something)
        return HttpResponse('Everything went OK.')
    
    def invalid(self, request, form):
        return render_to_response('errors_in_form.html', {'form': form})
    
    def unbound(self, request, form):
        return render_to_response('form_input.html', {'form': form})

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.