1

在这里开发我的第一个应用程序,我使用基于类的视图(django.views.generic.base.View)来处理来自网页的请求。

在网页上,我有不同的表单来发送 POST 请求,例如,有文本发布表单、评论表单、投票按钮等,我正在检查POST.has_key()哪个表单已发布并根据该表单进行处理。

有什么更好的方法吗?是否可以定义诸如 post_text、post_comment 等方法名称并配置 dispatch() 以相应地运行该方法?

4

1 回答 1

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
于 2013-09-20T22:53:22.847 回答