Login

Allow separation of GET and POST implementations

Author:
agore
Posted:
June 14, 2012
Language:
Python
Version:
1.4
Score:
2 (after 2 ratings)

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

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

Comments

cootetom (on June 14, 2012):

Nice example of "Simple is better than complex". I like it.

#

robbtolli (on July 16, 2012):

"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.