Reputation: 529
Developing my first application here and im using a class based view(django.views.generic.base.View
) to handle requests from a webpage.
On the webpage I have different forms that send out POST requests, for example, there is text posting form, comment form, vote button, etc. and Im checking POST.has_key()
to see which form has been posted and processing according to that.
Whats a better way to do it? And is it possible to define method names such as post_text, post_comment etc and configure dispatch() to run the method accordingly?
Upvotes: 2
Views: 213
Reputation: 141
I would do it like this:
class AwesomeView(View):
def post(self, request, *args, **kwargs):
# This code is basically the same as in dispatch
# only not overriding dispatch ensures the request method check stays in place.
# Implement something here that works out the name of the
# method to call, without the post_ prefix
# or returns a default method name when key is not found.
# For example: key = self.request.POST.get('form_name', 'invalid_request')
# In this example, I expect that value to be in the 'key' variable
handler = getattr(
self, # Lookup the function in this class
"post_{0}".format(key), # Method name
self.post_operation_not_supported # Error response method
)
return handler(request, *args, **kwargs)
def post_comment(self, request, *args, **kwargs):
return HttpResponse("OK") # Just an example response
Upvotes: 1