【问题标题】:I cant access the form "name" or "value" in request.POST in Django我无法在 Django 的 request.POST 中访问表单“名称”或“值”
【发布时间】:2017-10-23 20:41:41
【问题描述】:

我的模板包含多个带有多个按钮的表单。

我已经阅读了这些主题:

Proper way to handle multiple forms on one page in Django

How can I build multiple submit buttons django form?

How can I access the form submit button value in Django?

我做的完全一样,在表单的输入中包含“名称”和“值”(也尝试使用按钮标签)

但 POST 请求中不存在“名称”属性。我做错了什么?

模板:

<div class="container" align="center" style="border: solid 3px red">
    <h3>Form 1</h3>
    <form id="form_step_1" method="post" action="{% url 'ajax_order_data' %}" align="center">
            {% csrf_token %}
            {{ FormStep1 }}
            <button type="submit" name="step_1" value="step_1">button_step1</button>
    </form>
</div>

<br>

<div class="container" align="center"  style="border: solid 3px red">
    <h3>Form 2</h3>
    <form id="form_step_2" method="post" action="{% url 'ajax_order_data' %}" align="center">
            {% csrf_token %}
            {{ FormStep2 }}
            <button type="submit" name="step_2" value="step_2">button_step2</button>
    </form>
</div>

<script>
    var form_1 = $("#form_step_1");
    var form_2 = $("#form_step_2");

    form_1.submit(function(e){
        e.preventDefault();
        var url = $(form_1).attr('action');
        $.ajax({
          type: 'POST',
          url: url,
          data: form_1.serialize(),
          dataType: 'json',
          success: function (data) {smth_1}
        })
    });

    form_2.submit(function(e){
        e.preventDefault();
        var url = $(form_2).attr('action');
        $.ajax({
          type: 'POST',
          url: url,
          data: form_2.serialize(),
          dataType: 'json',
          success: function (data) {smth_2}
        })
    });
</script>

查看:

def somefunc(request):
if request.method == 'POST':
    if 'step_1' in request.POST:

【问题讨论】:

  • 你必须在末尾添加return render(request, template_name.html)

标签: python django forms


【解决方案1】:

您已明确禁用正常的表单提交过程,并在 Ajax 中以 JSON 格式发送数据。所以你不能使用 Django 中处理表单编码数据的常规方法,因为你没有。

相反,您需要反序列化请求的正文,这将为您提供一个字典:

data = json.loads(request.body)
if 'step_1' in data:

【讨论】:

    猜你喜欢
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 2011-01-10
    • 2011-06-03
    • 1970-01-01
    • 2016-12-24
    相关资源
    最近更新 更多