在Django中我想要一个带有2个提交按钮选项的表单。 “保存和回家”和“保存& next”。
我有什么想法可以确定在我的视图中点击了哪个提交按钮?
我很擅长编程/使用表单并欣赏反馈。
表格
<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})
答案 0 :(得分:26)
你可以给他们起名字。只需单击按钮即可通过提交发送数据。在模板中为它们指定适当的名称:
<button type="submit" name="save_home" value="Save&Home"> Save&Home</button>
<button type="submit" name="save_next" value="Save&Next"> Save&Next</button>
在相关部分的视图中,您可以通过检查其名称来检查点击了哪个按钮。
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'))
答案 1 :(得分:2)
在Django 2.x中,视图方法@FallenAngel的答案略有更改
if request.method == 'POST':
form = PriceAssessmentSection1(request.POST)
# Note change below
if 'save_home' in request.POST:
return HttpResponseRedirect(reverse('portal_home'))
# Note change below
elif 'save_next' in request.POST: # You can use else in here too if there is only 2 submit types.
return HttpResponseRedirect(reverse('portal_sec2'))