Django: How to access the display value of a ChoiceField in template given the actual value and the choices?

谁说我不能喝 提交于 2019-12-03 10:56:18
bmihelac

I doubt that it can be done without custom template tag or filter. Custom template filter could look:

@register.filter
def selected_choice(form, field_name):
    return dict(form.fields[field_name].choices)[form.data[field_name]]
Thibault J

Use the get_FOO_display property.

** Edit **

Oups! Quick editing this answer, after reading the comments below.

bound_form['field'].value()

Should work according to this changeset

in models

STATUS_CHOICES = (
    (0, _("Draft")),
    (1, _("Started")),
    (2, _("Stopped")),
)

class Study(models.Model):

    status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES, default=0)

    @property
    def get_status(self):
        return STATUS_CHOICES[self.status][1]

in your template (where you have passed the model instance as object)

{{ object.get_status }}

Check this link - https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display

You can use this function which will return the display name - ObjectName.get_FieldName_display()

Replace ObjectName with your class name and FieldName with the field of which you need to fetch the display name of.

I have a contact form using the FormView class-based view. The contact form has some ChoiceField fields. I'm not storing the submissions in the database; just emailing them to the site owner. This is what I ended up doing:

def form_valid(self, form):
    for field in form.fields:
        if hasattr(form[field].field, 'choices'):
            form.cleaned_data[field + '_value'] = dict(form[field].field.choices)[form.cleaned_data[field]]

    ...

If you use {{ form.instance.field }} in the form template, it should display the selected choice display name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!