Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Render label names instead of integer fields in Django templates

As part of my models, I have an IntergerField "choices".

These choices have been labelled. (Label 1 = Straw, Label 2 = Yellow…)

However, the HTML renders the integer rather than the actual labels.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What do I need to do return the labels and not the field’s interger?

Is it somethng I need to do in views? Or do I address it directly in the html file?

Code below:

Models

CHOICE1=(
    ('',''),
    (1,'Straw'),
    (2,'Yellow'),
)

class Model1(models.Model):
    user = models.ForeignKey(User,blank=True,on_delete=models.CASCADE)
    Choice_A = models.IntegerField(choices=Choice1,default=0)

Views

def account(request):
    review_list = Model1.objects.all
    return render(request,"main/account.html", {'review_list':review_list})

HTML

<h6>Champagnes</h6>
{% for Model1 in review_list%}
<table class="table table-hover table-striped table-bordered ">
    {% if Model1.user == user%}
    <tr>
        <th>Text</th><th>{{Model1.Choice_A }}</th>
    </tr>
{%endif%}
</table>
{% endfor %}

>Solution :

You need to use the following in your template:

{{ Model1.get_Choice_A_display }}

It will render the string instead of the integer

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading