Identify which submit button was clicked in Django form submit

老子叫甜甜 提交于 2020-07-17 07:18:07

问题


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

<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-->

View

@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})

回答1:


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'))



回答2:


In Django 2.x there is a slight change to the view method @FallenAngel's answer

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'))


来源:https://stackoverflow.com/questions/21505255/identify-which-submit-button-was-clicked-in-django-form-submit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!