Issue
i have an html form inclouds select input , and the option have extra attribute value called "testvalue" , and want to pass the "testvalue" to my views, and here is my example as the following :
<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 :
q_post_id = request.POST.get("q_post_id")
but this will give me a default value "{{post.item.id}}",
so how can i get the extra attribute in view ?
thanks.
Solution
i solve my problem by send "dictionary string" value from my html form ,
and then convert it to python dictionary in my view, and here my codes :
html form select option :
<select class="form-control select2" name="q_post_id" >
<option disabled selected >Select Post</option>
{% for post in all_posts %}
<option value='{ "postid_key" : "{{post.item.id}}" , "key2": "value2" }' > {{post.item.message}}</option>
{% endfor %}
</select>
in views.py:
import json
if request.method == "POST":
q_post_id = request.POST.get("q_post_id")
if q_post_id:
print(type(q_post_id))
q_post_id = json.loads(q_post_id)
print(type(q_post_id))
print(f"your postid_key is : {q_post_id['postid_key']}")
print(f"your key2 is : {q_post_id['key2']}")
the output :
<class 'str'>
<class 'dict'>
your postid_key is : 122431899774433
your key2 is : value2
done.
Answered By – K.A
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0