Arjun Krishna
Arjun Krishna

Reputation: 45

Access first value in tuple in Django Template HTML

I am creating a website in Django and need to display a value that the user had chosen from a choice field - their user_status which is stored in a tuple. The first and second values are identical, but they can be 'Member' or 'Expert'.

At first I tried this in my HTML:

{{ user.user_status }}

This was the result:

('Member', 'Member')

What I wanted was this:

Member

Next, I tried

{{ user.user_status.Member }}

The result was nothing:

Finally I tried

{{ user.user_status.Member.0 }}

The result was the first character in ('Member', 'Member')

(

How can I access either the first or second value of this tuple and display it in my HTML?

Edit 1:

My model:

class CustomUser(AbstractUser):
    __USER_STATUS = [('Member','Member'), ('Expert','Expert')]

    user_status = models.CharField(
        max_length = 20,
        choices = __USER_STATUS,
        default = __USER_STATUS[0], # 'Member'
    )
    phone_number = models.CharField(null=True, blank=True, max_length=30)

Edit 2:

Something strange is going on...

When I use: {{ user.user_status }}

It displays ('Member', 'Member') in the internet window opened by visual studio code.

But it displays Member in Firefox and Chromium.

Why is this?

Why is the same code showing different results in different browsers? I know that sometimes this happens with how the webpage looks, but this is a fundamental difference in content.

Thank you for your help!

Upvotes: 2

Views: 1187

Answers (2)

JPG
JPG

Reputation: 88509

It should be (provided, user.user_status should be an iterable)

{{ user.user_status.0 }}

Upvotes: 1

Biplove Lamichhane
Biplove Lamichhane

Reputation: 4095

I believe that data actually, is not a tuple, but a string. So,I am going to make tuple and get the tuple value from the models and return it back to the template via user_status_from_tuple.

models.py

class CustomUser(AbstractUser):
    ....

    def user_status_from_tuple(self):
        user_status = eval(self.user_status)
        return user_status[0]

In your template:

{{ user.user_status_from_tuple }}

Upvotes: 1

Related Questions