【问题标题】:Post method in djangodjango中的post方法
【发布时间】:2019-08-14 18:45:20
【问题描述】:

我在 django 中有一个带有表单的教程,我试图完全按照所教的去做,但我发现要么我的表单没有发送 post 方法,要么 django 无法意识到发送的请求是一个 POST 请求

这是我的名为“register.html”的文件:

{% extends "blog/base.html" %} 
{% block content %}
    <div class="content-section">
        <form role="form" method="post">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">Join Today</legend>
                {{ form.as_p }}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">Sign Up</button>
            </div>
        </form>
        <div class="border-top pt-3">
            <small class="text-muted">
                Already Have An Account? <a class="ml-2" href="#">Sign In</a>
            </small>
        </div>
    </div>
{% endblock content %}

这里是 django side views.py:

from django.shortcuts import render , redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages


def register (request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            messages.success(request, f'Account created for {username}!')
            return redirect('blog-home')
    else:
       form = UserCreationForm()
    return render(request, 'users/register.html' , {'form': form})

结果是当我点击提交时,POST方法不起作用,我尝试传递一个get请求并且它起作用了,所以只有当我尝试发送POST请求时才会出现问题,那么问题出在哪里? 在django的views.py中还是在html文件中?

【问题讨论】:

    标签: python html django


    【解决方案1】:

    在表单中添加操作 url

    <form role="form" action="/url/" method="post">
    

    参考this

    【讨论】:

      【解决方案2】:

      我同意@c.grey 的评论,如果表单有错误,那么视图将只返回表单,其中预先填写了表单数据以及与字段和表单关联的错误消息(您的错误可能不可见,因为到一些 CSS)。

      您也可以尝试使用 pdb 或 ipdb 等调试器查看执行路径。例如

      import ipdb; ipdb.set_trace()
      

      【讨论】:

        猜你喜欢
        • 2019-02-24
        • 2018-02-15
        • 2016-03-17
        • 1970-01-01
        • 2019-05-24
        • 2016-02-05
        • 2016-03-13
        • 2011-05-13
        • 1970-01-01
        相关资源
        最近更新 更多