Ticket #13972: form_utils.py

File form_utils.py, 728 bytes (added by Mitar, 14 years ago)

A function wich allows callables access to the request

Line 
1import inspect
2
3def initial_accepts_request(request, form_class):
4 """
5 If fields in the given form uses dynamic initial values which accepts request argument it wraps them so that request is given
6 to them when called.
7 """
8
9 initial = {}
10
11 for name, field in form_class.base_fields.items():
12 if callable(field.initial):
13 try:
14 if len(inspect.getargspec(field.initial)[0]) == 1:
15 # We fight Python aliasing in for loops here
16 initial[name] = (lambda fi: lambda: fi(request))(field.initial)
17 except:
18 pass
19
20 if not initial:
21 return form_class
22
23 def wrapper(*args, **kwargs):
24 initial.update(kwargs.get('initial', {}))
25 kwargs['initial'] = initial
26 return form_class(*args, **kwargs)
27
28 return wrapper
Back to Top