如何将 Django 模板中的额外自定义属性从 "select option" 表单传递到视图
how to pass extra custom attribute in Django template from "select option" form to a view
我有一个 html 表单,在 Django 模板中包含一个 select 输入,并且该选项有一个名为“testvalue”的额外属性值。
我想将“testvalue”属性传递给我的视图。
这是我在 Django HTML 模板中的示例:
<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>
通常在我的视图函数中,我使用以下代码获取输入值:
q_post_id = request.POST.get("q_post_id")
但这会给我一个默认值 "{{post.item.id}}"
。
如何在我的视图中获取额外的自定义属性值,即 'testvalue '?
<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">
然后在你的js中:
$('#q_post_id_select').on('change', function(e) {
$('#hiddenOption').val( $(this).find(':selected').data('testvalue') );
});
然后在 django 视图中发出请求后:
testvalue = request.POST.get("hiddenValue")
我有一个 html 表单,在 Django 模板中包含一个 select 输入,并且该选项有一个名为“testvalue”的额外属性值。
我想将“testvalue”属性传递给我的视图。
这是我在 Django HTML 模板中的示例:
<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>
通常在我的视图函数中,我使用以下代码获取输入值:
q_post_id = request.POST.get("q_post_id")
但这会给我一个默认值 "{{post.item.id}}"
。
如何在我的视图中获取额外的自定义属性值,即 'testvalue '?
<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">
然后在你的js中:
$('#q_post_id_select').on('change', function(e) {
$('#hiddenOption').val( $(this).find(':selected').data('testvalue') );
});
然后在 django 视图中发出请求后:
testvalue = request.POST.get("hiddenValue")