【问题标题】:Django Form request method is always GET, even method=“POST” is mentioned in HTML templateDjango 表单请求方法始终是 GET,甚至在 HTML 模板中提到了 method=“POST”
【发布时间】:2021-08-08 09:31:00
【问题描述】:

请帮我解决这个问题。我有一个项目要做... 谢谢!!

HTML 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Upload</title>
</head>
<body>
<form method="post" class="post-form" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="save btn btn-default">Save</button>
</form>
</body>
</html>

Views.py file

【问题讨论】:

  • 你会重新加载 Views.py 吗?我什么都看不见。
  • 是的,现在你可以看到它了

标签: python django django-views django-forms django-templates


【解决方案1】:

您应该在表单中添加“action”属性,以便服务器可以选择将数据发布到何处。将此属性添加到您的表单标签:

action="{% url 'url_name' %}"

url_name 这里是 urlpatterns 中用于接收表单请求的名称

例如:

urlpatterns = [
    path('url_name/', views.index, name = 'url_name'),
]

【讨论】:

    【解决方案2】:

    观看次数:

    def index(request):
        if request.method == 'POST':
            print("Valid")
            student = Studentform(request.POST, request.FILES)
            if student.is_valid():
                handle_uploaded_file(request.FILES['file'])
                student.save() # <== HERE 
                return HttpResponse('File uploaded successfully')
            else:
                return HttpResponse('Not uploaded')
        else:
            student = Studentform()
        return render(request, 'name_of_your_upload.html', {'student': student})
    

    模板:

        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>File Upload</title>
        </head>
        <body>
            <form method="post" class="post-form" enctype="multipart/form-data">
                    {% csrf_token %}
                    {{ student.as_p }}
                    <button type="submit" class="save btn btn-default">Save</button>
            </form>
        </body>
        </html>
    

    【讨论】:

    • 只有保存按钮可见其他组件不可见..
    • 我更新了答案,添加“student.save()”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    • 2015-07-16
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    相关资源
    最近更新 更多