确定在Django表单提交中单击了哪个提交按钮 [英] Identify which submit button was clicked in Django form submit

查看:281
本文介绍了确定在Django表单提交中单击了哪个提交按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中,我希望有一个带有2个提交按钮选项的表单。 保存并回家和保存并保存下一个。

In Django I would like to have a form with 2 submit button options. "save & home" and "save & next".

有人在想如何识别视图中单击了哪个提交按钮?

Any thoughts how I can identify which submit button was clicked in my view?

我对表单进行编程/处理还很陌生,感谢您的反馈。

I'm fairly new to programming/working with forms and appreciate the feedback.

表单

<form action="{% url 'price_assessment_section_1' component.id %}" method="post"> {% csrf_token %}

 {{ form.s1_q5_resin_type }}

 <!-- FORM SUBMIT BUTTONS-->

 <button type="submit" >&nbsp;Save&Home</button>

 <button type="submit" >&nbsp;Save&Next</button>

</form> <!-- end form-->

查看

@login_required
def price_assessment_section_1(request, component_id):

    component = Component.objects.get(id=component_id)

    if request.method == 'POST':
        form = PriceAssessmentSection1(request.POST)

                # if "save & home" go to: return HttpResponseRedirect(reverse('portal_home'))

                # if "save & next" go to: return HttpResponseRedirect(reverse('portal_sec2'))

    form = PriceAssessmentSection1()
    return render(request, 'portal/price_assessment_section_1.html', {'form': form, 'component':component})


推荐答案

您可以给它们命名。仅单击的按钮将其数据与提交一起发送。在您的模板中为其指定适当的名称:

You can give them names. Only clicked buttons send their data with submit. In your template give them appropriate names:

<button type="submit" name="save_home" value="Save&Home">&nbsp;Save&Home</button>
<button type="submit" name="save_next" value="Save&Next">&nbsp;Save&Next</button>

在相关部分的视图中,您可以通过选中按钮的名称来检查单击了哪个按钮。

And in your view in the related section, you can check which button is clicked by checkng its name.

if request.method == 'POST':
    form = PriceAssessmentSection1(request.POST)
    if request.POST.get("save_home"):
        return HttpResponseRedirect(reverse('portal_home'))
    elif request.POST.get("save_next"):  # You can use else in here too if there is only 2 submit types.
        return HttpResponseRedirect(reverse('portal_sec2'))

这篇关于确定在Django表单提交中单击了哪个提交按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆