JSRB
JSRB

Reputation: 2613

Value of Queryset doesn't populate template-tag in Django

I am missing a detail somewhere when trying to populate a simple template-tag with a value returned by a queryset.

Views.py

def render_cube_app(request, template="cube_app.html"):
    user_equity = serializers.serialize('json', Profile.objects.all())
    context = {
        'user_equity': user_equity
    }
    print(context)
    return render(request, template, context)

HTML

{% for user_equity in user_equity %}
  <p id="money_metrics_box_equity_figure">{{ user_equity.fields.equity }}</p>
{% endfor %}

which doesn't populate anything as of yet. Also I think I could get rid of the for-each loop basically?

Upvotes: 1

Views: 77

Answers (2)

iklinac
iklinac

Reputation: 15738

Firstly you are shadowing your own variable

{% for user_equity in user_equity %}

Instead of more convenient ( of course you should change context variable to plural also)

{% for user_equity in user_equities %}

Secondly you are using .fields property which probably doesn't exist

  <p id="money_metrics_box_equity_figure">{{ user_equity.equity }}</p>

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

You pass a JSON blob, so a string, not a list of dictionaries. Furthermore, please do not use the same variable name for both the iterator and the iterable.

You can parse the JSON blob to a list of dictionaries:

from json import loads as jsonloads

def render_cube_app(request, template="cube_app.html"):
    user_equity = jsonloads(serializers.serialize('json', Profile.objects.all()))
    context = {
        'user_equities': user_equity
    }
    print(user_equity)
    return render(request, template, context)

In the template, we then iterate over it, but better with a different name for the iterator than for the iterable:

{% for user_equity in user_equities %}
  <p id="money_metrics_box_equity_figure">{{ user_equity.fields.equity }}</p>
{% endfor %}

Upvotes: 1

Related Questions