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

  1. Hidden Forms by insin 8 years, 1 month ago
  2. Form row filter by kylefox 7 years, 6 months ago
  3. newforms self-contained login form by miracle2k 8 years, 1 month ago
  4. Template Filter attr by marinho 7 years, 4 months ago
  5. A Lazy ChoiceField implementation by lsbardel 5 years, 10 months ago

Comments

mark0978 (on April 21, 2009):

Maybe its just me, but I don't see how this is "DRY"er. Not even sure what the point of it is.

#

SmileyChris (on May 6, 2009):

Normally, you'd write:

if request.method == 'POST':
    form = MyForm(data=request.POST, files=request.FILES)
    if form.is_valid():
         form.save()
         # Redirect
else:
    form = MyForm()

Now you write:

form = MyForm(**form_kwargs(request))
if form.is_valid():
     form.save()
     # Redirect

#

SmileyChris (on April 25, 2010):

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.

The most simple case is (where files aren't involved and you always expect at least one thing in your POST):

form = MyForm(data=request.POST or None)
if form.is_valid():
    form.save()
    # Redirect

#

Please login first before commenting.