Django 在表单中呈现选择字段的显示名称

Django rendering display name of choice field in form

tl;dr:如何使表单输出模型中选项的“好”名称?

我有一个带有选择的 Django 模型,定义如下:

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,
    )

在forms.py中,widgets是这样定义的:

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(),
        }

表单本身是手动呈现的(尽管仅 {{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>

但是输出不是阿姆斯特丹,而是 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.

在其他模板中,我可以这样做:{{city.get_name_display}},以获得全名。如何在表单中执行此操作?

full code is here

在您的行 'city': forms.RadioSelect(), 中,您需要为其定义选项。它应该看起来像:

from blah.models import City

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(choices=City.CITY_CHOICES),
        }

radio select 小部件继承自 select 小部件,它在此处的文档中简要提及了 choices 参数:https://docs.djangoproject.com/en/1.10/ref/forms/widgets/#django.forms.Select

我从 reddit 用户 roambe 那里得到了following answer

由于city是外键,Django会使用City模型的__str__(或__unicode__)方法来选择标签。 这应该使它开始表现得像你想要的那样(如果需要,用 unicode 代替):

def __str__(self):
    return self.get_name_display()

我想稍微扩展一下这个论点,'work-around' 解决继承问题。

在我的情况下,returned 值从未从 'value' 更改为 'human-r'。我相信这取决于我的 db-django 配置:在我的数据库上,字段是 FK,但在 Django 上是一个简单的 CharField。这样,如果不对模型进行更改,我就无法为其定义 str 方法。 我决定,我只有 2-3 个选择,覆盖 get_status 函数以评估状态和 return 一个 'constant' 输出(一个简单的 IF 构造)。