确定在 Django 表单提交中点击了哪个提交按钮 [英] Identify which submit button was clicked in Django form submit
本文介绍了确定在 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" > Save&Home</button>
<button type="submit" > 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"> Save&Home</button>
<button type="submit" name="save_next" value="Save&Next"> 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屋!
查看全文