在此处开发我的第一个应用程序,并使用基于类的视图(django.views.generic.base.View
)来处理来自网页的请求。
在网页上,我有不同的表单发送POST请求,例如,有文本发布表单,评论表单,投票按钮等。我正在检查POST.has_key()
以查看已发布和处理的表单根据那个。
什么是更好的方法呢?是否可以定义方法名称,如post_text,post_comment等,并配置dispatch()以相应地运行方法?
答案 0 :(得分:1)
我会这样做:
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