Show only second field of the field choises

Asked

Viewed 29 times

-2

In my model I have an option list and when I display it in the template it appears like this: "("D", "Slow")" and I would like it to be displayed only "("Slow down")".

Currently

inserir a descrição da imagem aqui

As it should be

inserir a descrição da imagem aqui

Model.py

class Perfil(models.Model):
    vel = (
        ("D", "Devagar",),
        ("N", "Normal"),
        ("R", "Rápido "),
        ("S", "Super Rapido (Cuidado!)"),
    )

    velocidade = models.CharField(max_length=1, choices=vel, null=True, blank=True, verbose_name='Velocidade')

py views.

from django.shortcuts import render
from .models import Perfil

def account(request):
    user_id = request.user.id
    perfil = Perfil.objects.get(usuario_id=user_id)
    
    return render(request, 'core/account.html', {'nome': user_id, 'dados':perfil })

home html.

<select class="form-control select2 select2-hidden-accessible" style="width: 100%;" data-select2-id="1" tabindex="-1" aria-hidden="true">
    {% for opcao in dados.vel %}
        <option data-select2-id="{{opcao}}">{{ opcao }}</option>
    {% endfor %}
</select>

2 answers

2

As demonstrated in documentation of template for you can unpack (unpacking) the items you are iterating on.

As in your case, each item is a tuple, you could unpack the tuple into two values and use them:

<select class="form-control select2 select2-hidden-accessible" style="width: 100%;" data-select2-id="1" tabindex="-1" aria-hidden="true">
    {% for opcao_id, opcao_valor in dados.vel %}
        <option data-select2-id="{{ opcao_id }}">{{ opcao_valor }}</option>
    {% endfor %}
</select>

1

When you do it on the option you’re iterating inside a tuple of tuples, so I imagine you want to do it like this:

{% for opcao in dados.vel %}
    <option data-select2-id="{{opcao.0 }}">{{ opcao.1 }}</option>
{% endfor %}

Option.0 takes the first item of the tuple so in the case of the tuple ("D","Slow") it will take the "D" and 1 takes the second item of the tuple, in the case of the "Slow down"".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.