initial value for django form choice field ignored

我与影子孤独终老i 提交于 2019-12-22 02:30:42

问题


I have this form:

class UserUsesSourceForm(forms.Form):
    # some fields here
    username = forms.CharField(label=("Username"), max_length=30, help_text = ("Required"))
    provider = forms.ChoiceField(widget=forms.Select(), choices=SOURCES_CHOICES, initial=SOURCES_CHOICES[1])

The available choices are:

E = 'e'
A = 'a'
SOURCES_CHOICES = (
                  (A, 'A'),
                  (E, 'E'),
                  )

The view:

form = UserUsesSourceForm(initial={"username":request.user.username, 'provider':SOURCES_CHOICES[1]})return render_to_response('update_datasource.html', context_instance=RequestContext(request, params))

And the template:

<form action="" method="post">
    {% csrf_token %}
    {% if form.non_field_errors %}
    <p>
        {% for error in form.non_field_errors %}
            <div class="text-error">{{ error|escape }}</div>
        {% endfor %}
    </p>
    {% endif %}
    <div class="control-group">

        <label class="control-label" for="id_provider">Data source</label>
        <div class="controls">
            {{form.provider}}
        </div>
                </div>
</form>

The problem is that even if the initial value is correctly set, and I can test it in debug (i.e., the form "provider" field initial value is the tuple I want), the final html always show the first element in the select box:

<select name="provider" id="id_provider">
<option value="A">A</option>
<option value="E">E</option>
</select>

..while I'd expect it to have a "default" or "active" option. Please note that the username field is correctly initialized. How can I investigate further to find out where the problem is?


回答1:


You need to pass the option value instead of tuple in initial data:

form = UserUsesSourceForm(
    initial={'username':request.user.username,
             'provider':SOURCES_CHOICES[1][0]})


来源:https://stackoverflow.com/questions/15991501/initial-value-for-django-form-choice-field-ignored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!