access field value within Django template

Asked

Viewed 483 times

0

You can access the values within a variable in Django templates?

For example, I have this model:

 class Avaliacao(models.Model):
 post = models.TextField()
 data_inclusao = models.DataField()

in the field post is recorded data a Dict, this way:

 {'joao': ['gostei', 8], 'carla': ['nao gostei', 1] }

Let’s say in my/html template, I want to popular a table, how could I access the keys and values of that string ? Imagine that the data has been rendered to the data variable:

{% for avaliacao in dados %}
 {{ avaliacao.post }}
{% endfor %}

The way out would be:

<html>
<table>
    <thead>
	   <tr>
<th>Nome</th>
<th>Avaliacao: </th>
<th>Nota: </th>
    </tr>
	</thead>
	  <tr>
<td>JOAO</td>
<td>GOSTEI</td>
<td>8</td>
    <tr>
    <tr>
<td>CARLA</td>
<td>NAO GOSTEI</td>
<td>1</td>
    <tr>

</table>
</html>

  • A TextField text guard, no dict... If you’re using Dict before saving in the bank, just deserialize and use it as Dict...

  • @fernandosavio I know this, unfortunately the data is recorded the way I mentioned. What I would need was to pick up these strings. and form new variables. If in the template it is not possible el, you know how to create a function in the model, to call the function in the template ?

  • You do not specify what the serialization format is, but apparently it is JSON.. Just use module json python. Sopt already has enough content on this, take a look.

  • good, I’ll look. Thank you.

2 answers

1

Since the data type is a Dictionary, you can access it like this:

{% for key, values in dados.items %}
    {{ key }} 
    {% for item in values %}
        {{ item }} 
    {% endfor %}
{% endfor %}

NOTE: For the first one, you will access the key value of your Dict, as it is a Dict you have key/value, in value as you have an array, you need another to go through all the values of this.

0


I was able to solve creating a function in the model that returns the data in Json format, so I can call the function o in the template and navigate from Dict.

MODEL

class Avaliacao(models.Model):
post = models.TextField()
data_inclusao = models.DataField()

FUNCTION IN THE MODEL

@property
def post_dict(self):
    try:
        return json.loads(self. post)
    except ValueError:
        return {}

VIEW

 queryset = Avaliacao.objects.all()
{'dados': queryset}

TEMPLATE

{% for avaliacao in dados.post_dict.items %}
 {{ avaliacao.0 }}
 {{ avaliacao.1 }}
{% endfor %}

Browser other questions tagged

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