405在Django Form POST上不允许使用方法

时间:2020-03-11 16:12:48

标签: python django csv

每次我单击POST表单上的Submit按钮以上传CSV文件。我收到不允许的代码405方法。我已经尝试过更改其他导入方法,例如django_import_export,但仍然得到相同的响应(405)。请帮忙!

这是我的views.py:

class AdvisoryView(TemplateView):
    template_name = 'advisory.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["adv"] = Mobile.objects.all()
        return context

    def mobile_upload(request):
        template = "advisory.html"

        prompt = {
            'order': 'blah'
        }

        if request.method == "GET":
            return render(request, template, prompt)

        csv_file = request.FILES('file')

        if not csv_file.name.endswith('.csv'):
            messages.error(request, 'This is not a csv file')

        data_set = csv_file.read().decode('UTF-8')
        io_string = io.StringIO(data_set)
        next(io_string)
        for column in csv.reader(io_string, delimiter=',', quotechar='|'):
            _, created = Mobile.objects.update_or_create(
                mobile_owner=column[0],
                mobile_number=column[1],
            )
        context = {}
        return render(request, template, prompt)

和mobile.html看起来像这样。我实际上将表单放在模型表单中。

<div class="modal-body">            
    {% block content %}
    <form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="file">
    <p>Only accepts .csv file</p>
    <button type="submit">Upload</button>
    </form>
    {% endblock content %}
    </div>
    <div class="modal-footer">

,而urls.py是

from django.urls import path, include
from . import views
from .views import AdvisoryView, HomeView


urlpatterns = [
    path('', HomeView.as_view(), name='home'),
    path('advisory/', AdvisoryView.as_view(), name='advisory'),
]

1 个答案:

答案 0 :(得分:0)

此答案已解释了为什么TemplateView中不允许POST。 https://stackoverflow.com/a/44859716/11607969

您可能需要将功能mobile_upload更改为post