tl;dr: How do I make a form output the ‘nice’ name of the choices in a model?
I have a Django model with choices, defined like this:
class City(models.Model):
AMSTERDAM = 'AMS'
ROTTERDAM = 'ROT'
THE_HAGUE = 'THE'
UTRECHT = 'UTR'
CITY_CHOICES = (
(AMSTERDAM, 'Amsterdam'),
(ROTTERDAM, 'Rotterdam'),
(THE_HAGUE, 'The Hague'),
(UTRECHT, 'Utrecht'),
)
name = models.CharField(
max_length=3,
choices=CITY_CHOICES,
default=AMSTERDAM,
blank=False,
)
In forms.py, the widgets are defined like this:
class ArticleForm(ModelForm):
class Meta:
model = Article
fields = ['title', 'text', 'categories', 'city']
widgets = {'title': forms.TextInput(attrs={
'placeholder': 'Enter a descriptive title'}),
'text': forms.Textarea(attrs={'placeholder': 'The article'}),
'categories': forms.CheckboxSelectMultiple(),
'city': forms.RadioSelect(),
}
The form itself is rendered manually (although the same effect happens with just {{form}}
:
<form action="{% url 'article-submit' %}" method="POST">
{% csrf_token %}
{{% for field in form %}
<fieldset class="article-form__field">
{% if field.name = "categories"%}
{{ field.label_tag }}
<ul id={{ field.auto_id }}>
{% for checkbox in field %}
<li>
<label for="{{ checkbox.id_for_label }}">
{{ checkbox.choice_label }}
</label>
{{ checkbox.tag }}
</li>
{% endfor %}
</ul>
{% elif field.name = "city" %}
{{ field.label_tag }}
<ul id={{ field.auto_id }}>
{% for radio in field %}
<li>
<label for="{{ radio.id_for_label }}">
{{ radio.choice_label }}
</label>
{{ radio.tag }}
</li>
{% endfor %}
</ul>
{% else %}
{{ field.label_tag }} {{ field }}
{% endif %}
</fieldset>
{% endfor %}}
<fieldset class="article-form__field">
<input class="button" type="submit" value="submit">
</fieldset>
</form>
However the output is not Amsterdam, but AMS:
<fieldset class="article-form__field">
<label for="city_0">City:</label>
<ul id=city>
<li>
<label for="city_0">
---------
</label>
<input checked="checked" id="city_0" name="city" type="radio" value="" />
</li>
<li>
<label for="city_1">
AMS
</label>
<input id="city_1" name="city" type="radio" value="1" />
</li>
etc.
In other templates, I could do this: {{city.get_name_display}}
, to get the full name. How do I do this in the form?