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
- Template tag - list punctuation for a list of items by shapiromatron 9 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
Please login first before commenting.