Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

Django - Days of the week (int) isn't rendering a string

I have a model in my app that stores the a single day of the week as:


DAYS = (
        (0, 'Monday'),
        (1, 'Tuesday'),
        (2, 'Wednesday'),
        (3, 'Thursday'),
        (4, 'Friday')
    )

day = models.IntegerField(validators=[MaxValueValidator(4), MinValueValidator(0)], blank=True, choices = DAYS)

According to the Django Documentation,:

The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name

However, that doesn't seem to be the case for me. For instance, in this template here in the same app, when I have something like:

{{q.day}}

This gives me: 1 instead of Tuesday. I tried some suggestions from SO, including creating your own model, and even considered passing custom functions through Jinja2, though I feel this to be unnecessarily complex. What would be the best way to go about this. Do I not understand the functionality of this clearly?

Note: I want to store the day to be int because my app is running some complex algorithms and I want to just convert it for display purposes.

question from:https://stackoverflow.com/questions/65901471/django-days-of-the-week-int-isnt-rendering-a-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try:

{{ q.get_day_display }}

(without parenthesis in the template)

https://docs.djangoproject.com/fr/3.1/ref/models/instances/#django.db.models.Model.get_FOO_display


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...