Login

DRYer instantiation of Forms

Author:
SmileyChris
Posted:
April 7, 2009
Language:
Python
Version:
1.0
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 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.