none if empty list decorator

 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. Alternative to Captchas (Without Human Interaction) by Archatas 4 years, 7 months ago
  2. use oldforms validators in newforms forms by garywilson 6 years, 1 month ago
  3. Allow separation of GET and POST implementations by agore 11 months, 1 week ago
  4. Updated version of #31 by ubernostrum 6 years, 2 months ago
  5. Profanity Check by menendez 3 years, 10 months ago

Comments

(Forgotten your password?)