'how to pass extra custom attribute in Django template from "select option" form to a view

I have an html form include a select input in Django template, and the option has an extra attribute value called "testvalue".

I want to pass the "testvalue" attribute to my views.

Here is my example in Django HTML template:

<select  class="form-control select2" name="q_post_id"  >

    <option disabled selected >Select Post</option>

    {% for post in all_posts %}

        <option value="{{post.item.id}}" testvalue = "my test value" >  {{post.item.message}}</option>

    {% endfor %}

</select>

Normally in my view function I use the following code to get to input value:

q_post_id = request.POST.get("q_post_id")

but this will give me a default value "{{post.item.id}}".

How can I get the extra custom attribute value in my view which is the 'testvalue '?



Solution 1:[1]

<select  class="form-control select2" name="q_post_id" id="q_post_id_select"  >
    <option disabled selected >Select Post</option>
    {% for post in all_posts %}
        <option value="{{post.item.id}}" data-testvalue = "my test value" >  {{post.item.message}}</option>
    {% endfor %}
</select>

<input type="hidden" name="hiddenValue" id="hiddenOption">

Then in your js:

$('#q_post_id_select').on('change', function(e) {
  $('#hiddenOption').val( $(this).find(':selected').data('testvalue') );
});

Then after you make the request in django view:

testvalue = request.POST.get("hiddenValue")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lucutzu33