Django 预填充 HTML MultieChoice 字段

Django Prepopulate HTML MultieChoice Field

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

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>

在每个选项中,您可以检查该选项是否在 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>

根据您的项目,您可以采用您认为更适合您的目的的方式。

第一: Django.forms.ModelMultipleChoiceField or Django.forms.MultipleChoiceField

@Nazkter 的

2nd: 不错,

第三:

html
(我向 select 添加了一个 states 属性,其中包含 {{ states }} 的值)

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

javascript

[].forEach.call(document.querySelectorAll('#id_states option')  , function(elm){
    var states = document.querySelector('#id_states').getAttribute("states").replace(/\s/g,'').split(",");
    if(states.indexOf(elm.innerText) > -1){
        elm.selected = true;
    }
});