Django does not have a clean, built-in mechanism to separate GET and POST implementations. This simple decorator provides this behavior. Django does provide an alternate way using class-based views, but defining class for each of your view functions may be an overkill. You can name the get and post functions anything you wish, but you need to make sure they are returned in the same order (get first and then post).
Example usage:
@formview
def edit(request, id):
form = EditForm(id, request.POST or None)
def get():
return render(request, 'edit.html', {'form' : form})
def post():
if form.is_valid():
form.save(id)
return redirect('list')
return get, post
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 | def formview(func):
"""
Decorator for separating GET and POST implementations
Example:
@formview
def viewfunction(request):
#Write code which needs to be called for both
def get():
#return GET view to be rendered
def post():
#return view after form POST
#Make sure to return get, post functions in the same order
return get, post
"""
def wrapped(request, *args, **kargs):
get, post = func(request, *args, **kargs)
if request.method == "POST":
return post()
else:
return get()
return wrapped
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Nice example of "Simple is better than complex". I like it.
#
"Django does not have a clean, built-in mechanism to separate GET and POST implementations."
Yes it does. Use a class based view and derive your class from ProcessFormView. Then, simply define get() and post() methods.
See the Django ProcessFormView docs.
#
Please login first before commenting.