POST请求被判定为NOT POST方法

时间:2018-05-15 23:19:10

标签: python django

当我从表单提交帖子请求时,它会被处理为不在帖子中发布:

<p>Edit The Topic:</p>
<form  action="{% url "learning_logs:edit_topic" topic.id %}" method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <button name="button">Save Changes</button>
</form>

views.py,我在if request != "POST":

中设置了测试
def edit_topic(request, topic_id):
    topic = Topic.objects.get(id=topic_id)

    if request != "POST":
        form = TopicForm(instance=topic)
        # assert request == 'POST'

        print("\tPOST Method in not post condition.\n",
             f"\tRequest Method is {request.__dict__['method']}")

来了

Quit the server with CONTROL-C.
    POST Method in not post condition.
    Request Method is POST
[16/May/2018 07:14:31] "POST /edit_topic/5 HTTP/1.1" 200 1770

post方法被视为不发布。

我的代码有什么问题?

2 个答案:

答案 0 :(得分:2)

检查请求方法的正确方法是request.method

if request.method == 'POST':

您目前正在做的是检查请求对象是否为字符串'POST',而不是因为它是Django提供的Request object对你而言。

答案 1 :(得分:2)

假设请求为request类型,请尝试改为:

def edit_topic(request, topic_id):
  topic = Topic.objects.get(id=topic_id)

  if request.method != "POST":
    form = TopicForm(instance=topic)
    # assert request == 'POST'

    print("\tPOST Method in not post condition.\n", f"\tRequest Method is {request.__dict__['method']}")