def process_form request FormClass args kwargs Form processing helpers

 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
def process_form(request, FormClass, *args, **kwargs):
"""Form processing helpers allowing to keep DRY in views.
Arguments:
- ``request``: HttpRequest instance
- ``FormClass``: form to process
- ``dest_url``: destination url to redirect after successful form saving.
If it is not present, then the method ``get_absolute_url`` of object
returned by form will be used. In case of its unavailability user will be
redirected to current page.
- ``on_success``: function to run if form was successfully saved, should
receive single argument (form's output).
- ``no_redirect``: do not return redirect response after successfull save.
``dest_url`` and ``on_success`` should always be keyword arguments. All
other arguments are passed directly to FormClass' init.
Requires RedirectMiddleware (to catch RedirectException).
"""
if not FormClass:
return None
dest_url = kwargs.pop('dest_url', None)
on_success = kwargs.pop('on_success', None)
no_redirect = kwargs.pop('no_redirect', None)
if request.method == 'POST':
form = FormClass(data=request.POST, files=request.FILES, *args, **kwargs)
if form.is_valid():
obj = form.save()
if not dest_url and hasattr(obj, 'get_absolute_url'):
dest_url = obj.get_absolute_url()
if on_success:
on_success(obj)
if not no_redirect:
raise RedirectException(dest_url or '.')
else:
form = FormClass(*args, **kwargs)
return form