Login

none if empty list decorator

Author:
laxu
Posted:
August 27, 2008
Language:
Python
Version:
.96
Tags:
decorator list empty none
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. custom template filter to check if list contains any non-empty element by doniyor 12 months ago
  2. Profanity Check by menendez 6 years, 1 month ago
  3. Get object/list or None by lokesh 5 years, 12 months ago
  4. Url persistance of GET variables by alex_ndc 6 years, 9 months ago
  5. Language aware cache decorator by bartTC 6 years, 4 months ago

Comments

Please login first before commenting.