Login

none if empty list decorator

Author:
laxu
Posted:
August 27, 2008
Language:
Python
Version:
.96
Score:
-3 (after 5 ratings)

this avoids checking if POST contains data for forms. see source for usage example

 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
def none_if_empty_list(f):
        def func(*args, **kwargs):
                if len(args)>1 and args[1]=={}:
                        args=[arg for arg in args]
                        args[1]=None
                return f(*args, **kwargs)
        return func

#use this decorator on your forms like this:

class myForm(forms.Form):
	@none_if_empty_list
	def __init__(self, *args, **kwargs):
		forms.Form.__init__(self, *args, **kwargs)

#and use the model this way:

def myview(request):
	form=myForm(request.POST)

#if the request is NOT post, the form will just be empty. If it is post and some values #are missing/wrong, you will get the errors like always. This avoids code linke this:

def myview(request):
	if request.method=="POST":
		form=myForm(request.POST)
	else:
		form=myForm()

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.