Login

DRYer instantiation of Forms

Author:
SmileyChris
Posted:
April 7, 2009
Language:
Python
Version:
1.0
Tags:
forms
Score:
1 (after 3 ratings)

Using this small helper, you can instanciate your forms in an even DRYer way:

form = MyForm(**form_kwargs(request))
if form.is_valid():
    #...
1
2
3
4
5
6
def form_kwargs(request):
    kwargs = {}
    if request.method == 'POST':
        kwargs['data'] = request.POST
        kwargs['files'] = request.FILES
    return kwargs

More like this

Comments

mark0978 (on April 21, 2009):
<p>Maybe its just me, but I don't see how this is "DRY"er. Not even sure what the point of it is.</p>

#

SmileyChris (on May 6, 2009):
<p>Normally, you'd write:</p> <pre>if request.method == 'POST': form = MyForm(data=request.POST, files=request.FILES) if form.is_valid(): form.save() # Redirect else: form = MyForm() </pre> <p>Now you write:</p> <pre>form = MyForm(**form_kwargs(request)) if form.is_valid(): form.save() # Redirect </pre>

#

SmileyChris (on April 25, 2010):
<p>PS: if you'd rather not bother with a helper like this, the method of instanciating a form only once for both cases is still useful.</p> <p>The most simple case is (where files aren't involved and you always expect at least one thing in your POST):</p> <pre>form = MyForm(data=request.POST or None) if form.is_valid(): form.save() # Redirect </pre>

#

Please login first before commenting.