如何使Django模型选择字段易于阅读

时间:2019-01-20 21:30:11

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

所以我有几个月的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个而不用一个月

2 个答案:

答案 0 :(得分:1)

使用get_<field_name>_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

答案 1 :(得分:0)

作为回报,您需要将monthEntry发送到前端:

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