Login

Allow separation of GET and POST implementations

Author:
agore
Posted:
June 14, 2012
Language:
Python
Version:
1.4
Tags:
get decorator post
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. PK->objects in view signature by AdamKG 7 years, 1 month ago
  2. prevent GET or POST requests by jerzyk 7 years, 5 months ago
  3. EasyFeed class by limodou 8 years, 2 months ago
  4. Decorator that limits request methods by schinckel 5 years, 10 months ago
  5. Auto rendering decorator with options by Batiste 7 years, 4 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.