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

标签 python django django-forms jinja2

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 中,小部件是这样定义的:

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>

但是输出不是 Amsterdam,而是 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

最佳答案

我得到了 following answer来自 reddit 用户 roambe:

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

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

关于python - Django 在表单中呈现选择字段的显示名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38751300/

相关文章:

python - 按 drf 中的价格总和排序查询集

python - 使用模型名称字符串输入查询 Django 模型

基于 Django 类的 View : Posting form data returns 302 Found status code

python - 使用 xlwt 卡住 excel 中的单元格

Python:Pandas 样式背景颜色在 Excel 文件中不可见

python - 10折交叉验证python单变量回归

python - 如何在 Python 中初始化一个二维数组?

python - 在 Django 管理员中,添加通用关系的内联

python - Django CreateView self.object 返回 None

python - 在 Django 中使用表单