【问题标题】:How to display a ChoiceField's text through Django template to a user?如何通过 Django 模板向用户显示 ChoiceField 的文本?
【发布时间】:2022-01-16 19:40:19
【问题描述】:

models.py:

class Person(models.Model):
    title=models.CharField(max_length=11)
    name=models.CharField(max_length=100)
    gender=models.CharField(max_length=11)

forms.py:

class PersonForm(ModelForm):
    GENDER_SELECT = (
        ('f', 'Female'),
        ('m', 'Male'),
        ('o', 'Other'),
    )
    TITLE_SELECT = (
        ('0', 'Mr.'),
        ('1', 'Mrs.'),
        ('2', 'Ms.'),
        ('3', 'Mast.'),
    )
    title=forms.CharField(widget=forms.RadioSelect(choices=TITLE_SELECT, attrs={'class': 'form-check-inline'}))
    gender=forms.CharField(widget=forms.RadioSelect(choices=GENDER_SELECT, attrs={'class': 'form-check-inline'}))
    class Meta:
        model=Person
        fields='__all__'

现在,下面是我尝试将数据输出到网页的两种方法,但第一种方法不返回任何内容,第二种方法返回选择的数据库值,而不是用户输入的文本选择。我希望用户看到 Mr. or Mrs. or Ms. or Mast。而不是 0/1/2/3。这里有什么问题?

模板:

1

{% for rp in report %}
<td class="design">{% if rp.title == 0 %} Mr. {% elif rp.title == 1 %} Mrs. {% elif rp.title == 2 %} Ms. {% elif rp.title == 3 %} Mast. {% endif %}</td>
{% endfor %}

2

{% for rp in report %}
    <td class="design">{{rp.title}}</td>
{% endfor %}

【问题讨论】:

  • 请编辑问题以显示您的观点。

标签: django django-templates


【解决方案1】:

第一个解决方案不起作用,因为 titlestr 并且您将它与整数进行比较。以下将起作用:

{% for rp in report %}
<p>
    {% if rp.title == '0' %}
        Mr.
    {% elif rp.title == '1' %}
        Mrs.
    {% elif rp.title == '2' %}
        Ms.
    {% elif rp.title == '3' %}
        Mast.
    {% endif %}
</p>
{% endfor %}

更好的解决方案是创建一个template tag

# templatetags/report_tags.py
from django import template

register = template.Library()

titles = {
    '0': 'Mr.',
    '1': 'Mrs.',
    '2': 'Ms.',
    '3': 'Mast.',
}

@register.simple_tag
def person_title(title):
    return titles.get(title)

在你的模板里面:

{% load report_tags %}

{% for rp in report %}
<td class="design">
    {% person_title rp.title %}
</td>
{% endfor %}

干净多了!

【讨论】:

    猜你喜欢
    • 2019-11-12
    • 2012-07-05
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 2011-08-13
    • 2020-03-07
    相关资源
    最近更新 更多