new to dj coming over from flask.
I’m having trouble accessing the elements that I passed to the django template.
here is the abstract structure of the data:
list[{dict_key: <QuerySet[]>,…},…]
auctions=[{"auction": Auction.objects.filter(is_active=True).order_by('-end_date')},]
in this case (in python syntax) auctions[0][‘auction’] should return a model object, one of whos properties would be named ‘is_active’, and who’s value =True
my problem is that I cant seem to figure out how to do this in a django template.
tried:
<h3>Auction Title: {{auctions|first.auction.title}}</h3>
dj said: Could not parse the remainder: ‘.auction.title’ from ‘auctions|first.auction.title’
<h3>Auction Title: {{auctions|first[auction].title}}</h3>
dj said: Could not parse the remainder: ‘[auction].title’ from 'auctions|first[auction].title
not sure which direction to go here.
any suggestions would be appreciated, thx
So if auctions
is an entry in the context (e.g., context = {'auctions': auctions}
Then, based upon the information documented at The Django template language | Django documentation | Django,
{{ auctions }}
is a reference to the list.
{{ auctions.0 }}
is a reference to the first member of the list.
{{ auctions.0.auction }}
is a reference to the queryset being passed.
{{ auctions.0.auction.0 }}
is a reference to the first entry of the queryset.
{{ auctions.0.auction.0.is_active }}
would then be a reference to that attribute of that first entry in the queryset.
Now, note that you cannot replace either of those 0
s with a variable, the Django template rendering engine does not work that way. The expectation is that you would be iterating over those lists.
For example, {% for an_auction in auctions %}
will iterate over the list in the context. Each iteration through that loop will give you a reference to a different instance a dict in that loop.
Inside that loop then, {{ an_auction.auction }}
is a reference to the queryset. You can iterate over it using something like {% for each_auction in an_auction %}
, and {{ each_auction }}
will be a reference to an instance of Auction
.
1 Like
this(my ham fisted solution) was rather log winded, but works. I’d still be interested in learning how to step through this structure more directly if possible.
{% for auct in auctions %}
{% for key, value in auct.items %}
{%if key == 'auction'%}
<h3>Auction Listing #{{value.pk}}</h3>
{% endif %}
{% endfor%}
{% endfor %}
You’ve basically got it.
However, it may not be necessary to have that if
statement in there. Trying to reference an attribute that does not exist does not generated an error, and so it would be more performant to just try accessing it as auct.auction
, and iterating over it.
(Keep in mind that your queryset can return multuple entries, and so that key auction
is something that would need to be iterated over.)
1 Like