abhivemp
abhivemp

Reputation: 932

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.

Upvotes: 0

Views: 93

Answers (2)

Fabe
Fabe

Reputation: 759

When you have a choice in you model field you must use {{object.get_attribut_display}} not {{object.attribut}}. Don't forget to read documentation carefully.

Upvotes: 1

stellasia
stellasia

Reputation: 5612

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

Upvotes: 2

Related Questions