Django预填充HTML MultieChoice字段

时间:2018-05-01 03:00:47

标签: html django selected

预填充多项选择字段的最佳方法是什么。在我看来,我在上下文中添加了字段的值。

def get_context_data(self, *args, **kwargs):
    context = super(UserProfileUpdateView, self).get_context_data(*args, **kwargs)
    context['mystates']=user.states

输出

Alaska, Arizona, Alabama,

Hmtl页面

<div class="form-group">
    <label for="id_states">Add State 2:</label> <select name="states" id="id_states"  multiple="multiple">
    {% include "accounts/snippets/states_drop_down_options.html" %}
    </select>
</div>

state_drop_down_options.htmlm

  <option value="AL">Alabama</option>    
  <option value="AK">Alaska</option>    
  <option value="AZ">Arizona</option>    
  <option value="AR">Arkansas</option>    
  <option value="CA">California</option>

2 个答案:

答案 0 :(得分:1)

在每个选项中,您可以检查该选项是否在mystates变量中:

  <option value="AL" {% if 'Alabama' in mystates %}selected{% endif%}>Alabama</option>    
  <option value="AK" {% if 'Alaska' in mystates %}selected{% endif%}>Alaska</option>    
  <option value="AZ" {% if 'Arizona' in mystates %}selected{% endif%}>Arizona</option>    
  <option value="AR" {% if 'Arkansas' in mystates %}selected{% endif%}>Arkansas</option>    
  <option value="CA" {% if 'California' in mystates %}selected{% endif%}>California</option>

答案 1 :(得分:0)

根据您的项目,您可以按照自己的目的更好地思考。

<强>第一Django.forms.ModelMultipleChoiceFieldDjango.forms.MultipleChoiceField

@nazkter的

第二次The answer是个好人,

<强>第三

HTML
(我向ancestor::*[word][1]添加states属性,其中包含值select

{{ states }}

的javascript

<select name="states" states="{{ states }}" id="id_states"  multiple="multiple">
    {% include "accounts/snippets/states_drop_down_options.html" %}
</select>