【问题标题】:How to make django model choice field human readable如何使 django 模型选择字段具有人类可读性
【发布时间】:2019-06-14 07:46:35
【问题描述】:

所以我有几个月的 django 模型选择字段

class EntrySummary(models.Model):

    JANUARY = '1'
    FEBRUARY = '2'
    MARCH = '3'
    APRIL = '4'
    MAY = '5'
    JUNE = '6'
    JULY = '7'
    AUGUST = '8'
    SEPTEMBER = '9'
    OCTOBER = '10'
    NOVEMBER = '11'
    DECEMBER = '12'

    MONTH_CHOICES = (
        (JANUARY, 'January'),
        (FEBRUARY, 'February'),
        (MARCH, 'March'),
        (APRIL, 'April'),
        (MAY, 'May'),
        (JUNE, 'June'),
        (JULY, 'July'),
        (AUGUST, 'August'),
        (SEPTEMBER, 'September'),
        (OCTOBER, 'October'),
        (NOVEMBER, 'November'),
        (DECEMBER, 'December'),
    )

    name = models.CharField(
        max_length=255
    )
    month = models.CharField(
       max_length=2,
       choices = MONTH_CHOICES,
       default=JANUARY,
    )

Views.py 我渲染它

def based_onmonth(request, *args, **kwargs):
    monthId = request.GET.get('month')
    monthEntry = EntrySummary.objects.filter(month=monthId)
    return render(request, 'app/js_templates/month_dropdown_list.html', {'MonthItem': monthId})

html模板:

<option value="">---------</option>
{% for item in MonthItem %}
    <p>item.name</p>
<option value="{{ item }}">{{ item }}</option>
{% endfor %}

这样做我会在我的选择部分收到 {'month': '2'}

我的问题是如何在没有月份的情况下只打印 2 个

【问题讨论】:

  • 您正在发回您从 request.GET 在您的视图中获得的monthId。那你for循环了吗?!这里看起来有些不对。

标签: django django-models django-templates django-views


【解决方案1】:

使用get_&lt;field_name&gt;_display机制:

# Return the right thing from your view.
return render(request, 'app/js_templates/month_dropdown_list.html', {'MonthItem': monthEntry})

在你的模板中:

{% for item in MonthItem %}
    <option value="{{ item.month }}">{{ item.get_month_display }}</option>
{% endfor %}

参考:https://docs.djangoproject.com/en/2.1/ref/models/instances/#django.db.models.Model.get_FOO_display

【讨论】:

  • {{ month.get_name_display }} 显示空白,没有任何文字。
  • 如果回答对您有帮助,请记得点赞或选择,谢谢。
【解决方案2】:

在您的退货中,您需要将monthEntry 发送到前端:

return render(request, 'app/js_templates/month_dropdown_list.html', {'MonthItem': monthEntry})

【讨论】:

    猜你喜欢
    • 2018-06-01
    • 1970-01-01
    • 2018-07-30
    • 2017-04-19
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    相关资源
    最近更新 更多