基于类的视图中的错误405

时间:2016-12-12 08:56:06

标签: python django

我继续在django的网页上收到405错误。

views.py

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.parsers import FileUploadParser

# Create your views here.
class FileUploadView(APIView):
    #parser_classes = (FileUploadParser,)
    template_name = "list.html"
    # def put(self, request, filename, format=None):
    #     file_obj = request.data['file']
    #     # ...
    #     # do some stuff with uploaded file
    #     # ...
    #     return Response(status=204)

urls.py

from django.conf.urls import url
from rest_framework import renderers
from views import FileUploadView
urlpatterns = [
    url(r'', FileUploadView.as_view()),
]

list.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Minimal Django File Upload Example</title>
    </head>

    <body>
        <!-- List of uploaded documents -->
        {% if documents %}
            <ul>
                {% for document in documents %}
                    <li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li>
                {% endfor %}
            </ul>
        {% else %}
            <p>No documents.</p>
        {% endif %}

        <!-- Upload form. Note enctype attribute! -->
        <form action="{% url "list" %}" method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <p>{{ form.non_field_errors }}</p>

            <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>

            <p>
                {{ form.docfile.errors }}
                {{ form.docfile }}
            </p>

            <p><input type="submit" value="Upload"/></p>
        </form>
    </body>

</html>

不确定我是否需要发布更多代码。

但我继续在获取请求时收到405错误。我可以知道我做错了什么,或者我需要发布更多信息。

感谢。

1 个答案:

答案 0 :(得分:2)

尝试在类中定义get()方法:

def get(self, request):
    return Response(code=200)

正如docs所说:

  

使用API​​View类与使用常规View类几乎相同,像往常一样,传入的请求被分派到适当的处理程序方法,例如.get()或.post()

但是APIView类没有get()方法,所以任何GET请求calls http_method_not_allowed()方法。