Call django function on HTML button

Viewed 497

I want to call a django function on my Proceed button and pass the selected value to that function, how can I do that ?

Here's the form:

<select id="the-id">
        {% for i in z %}
        <option value="{{ i }}">{{ i }}</option>
        {% endfor %}
        <form method="post" novalidate>
            {% csrf_token %}
             <a class="btn btn-outline-secondary" role="button">Proceed</a>
            <a href="{% url 'employee:products_table' %}" class="btn btn-outline-
        secondary" role="button">Nevermind</a>
        </form>
    </select>

views.py

def warehouse_details(request):
    queryset = AllotmentDocket.objects.filter(send_from_warehouse = #to be fetched from the form)
    print("queryset is ", queryset)

    return render(request, 'packsapp/employee/allotwarehousedetails.html', {'query': queryset})

Urls.py

    path('warehouse-details/', warehouse_details, name='warehouse_details'),
1 Answers

Firstly, fix your HTML. The select needs to be inside the form, and have a name attribute; and the button needs to be an actual button, not a link styled to look like one.

<form method="post" novalidate>
    {% csrf_token %}
    <select id="the-id" name="my-select">
    {% for i in z %}
        <option value="{{ i }}">{{ i }}</option>
    {% endfor %}
    </select>
    <button type="submit" class="btn btn-outline-secondary" role="button">Proceed</button>
    <a href="{% url 'employee:products_table' %}" class="btn btn-outline-secondary" role="button">Nevermind</a>
</form>

Now you can get the data in the view using the name:

value = request.POST['my-select']

(However I would recommend you use Django forms; that will output the select for you and validate the response.)

Edit If you want to submit to a different URL to the one that displayed the form in the first place, you need to put it as the form action:

<form method="post" action="{% url 'warehouse_details' %}" novalidate>

assuming your URL pattern is named 'warehouse_details'.

Related