Question

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?

Was it helpful?

Solution

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]})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top