基于 Django class 的 post 视图

Django class based post-only view

很抱歉,如果这是一个微不足道的问题,但我已经搜索了很长时间,但一直无法找到一个好的实现。

有人可以提供一个示例,说明如何通过子类化任何通用视图在 Django 中实现仅 post 的视图(可以处理文件上传)吗?

我想创建一个端点来处理所有博客 post 评论创建逻辑。评论表单嵌入在我的博客页面上,因此,此数据将作为 POST.

发送到 url

我想这样的事情应该可行:

class TestView(View):

    def post(self, request):
        return HttpResponse('This is a post only view')

如果您使用 Django Rest Framework,您也可以使用 CreateAPIView 来完成此操作 http://www.django-rest-framework.org/api-guide/generic-views/#createapiview

Used for create-only endpoints.

Provides a post method handler.

您可以尝试类似的方法:

class MyView(TemplateView):
    template_name = 'my_template.html'

    def post(self, request, **kwargs):
        my_data = request.POST
        # do something with your data
        context = {}  #  set your context
        return super(TemplateView, self).render_to_response(context)

来自docs

dispatch looks at the request to determine whether it is a GET, POST, etc, and relays the request to a matching method if one is defined, or raises HttpResponseNotAllowed

所以基本上,您创建的任何基于 class 的视图,您只定义了一个 POST 方法,将只允许一个 POST 请求。

View class 有一个 http_method_names 属性,它列出了视图将接受的 HTTP 方法。

因此,您可以子class 任何您喜欢的通用视图(例如 CreateView),并设置 http_method_names 以便只允许 POST 请求。

from django.views.generic.edit import CreateView


class CommentCreateView(CreateView):
    http_method_names = ['post']
    model = Comment
    ...

或者,您可以子class View,并编写您自己的 post 方法。

class CommentView(View):

    def post(self, request):
        ...

在这种情况下,GET 请求将 return 一个 HttpResponseNotAllowed 响应,因为您还没有定义 get 方法来处理 GET 请求。

有一个内置的装饰器:require_POST(). More generically, you can use require_http_methods()

对于基于函数的视图(从文档中复制):

from django.views.decorators.http import require_http_methods

@require_http_methods(["GET", "POST"])
def my_view(request):
    # I can assume now that only GET or POST requests make it this far
    # ...
    pass

基于 class 的观看次数:

from django.utils.decorators import method_decorator
from django.views.decorators.http import require_http_methods

@method_decorator(require_http_methods(["GET", "POST"]), name='dispatch')
class MyView(View):
    # I can assume now that only GET or POST requests make it this far
    # ...
    pass