2

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

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

I tried it, the proceed button just refreshes the page, it does not redirect me to the next function.
Thanks for saving the day!, Can I pass other things from my form to that function too?.. I was thinking of adding a date field in the form and pass it to the function too
Sure, you can put as many fields in the form as you like. Just remember to give them all name attributes and use that name to access the data from the POST dict. But again I would really recommend you look into Django forms which take care of building the HTML and validating the submission.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.