How to access the 'rank' to a template which i have assigned for sorting objects in my Django views? -
i have created rank attribute 'amount' object in django project views. page. tried {{ bid.rank }}
in template. couldn't able rank particular 'amount' in template. please me how can rank value in page.
here code:
views.page:
def bid_list(request): queryset = bid.objects.all().order_by('amount') current_rank = 1 counter = 0 bid in queryset: if counter < 1: # first bid bid.rank = current_rank else: # other bids if bid.amount == queryset[counter - 1].amount: # if bid , previous bid have same score, # give them same rank bid.rank = current_rank else: # first update rank current_rank += 1 # assign new rank bid bid.rank = current_rank counter += 1 context = { "bid.rank" : "current_rank", "object_list": queryset, "title": "list" } return render(request, 'bid_list.html', context)
bid_list.html:
<table cellspacing="1" id="mytable" class="table table-striped" > <thead> <tr> <th>user</th> <th>amount</th> <th>rank</th> </tr> </thead> {% obj in object_list %} <tbody> <tr> <td>{{obj.user}}</td> <td>{{obj.amount}}</td> {% bid in bid.rank %} <td>{{bid.rank}}</td> {% endfor %} </tr> </tbody> {% endfor %} </table>
update - 1 :
html:
{% obj in object_list %} <tbody> <tr> <td>{{obj.user}}</td> <td>{{obj.amount}}</td> <td>{{obj.rank}}</td> </tr> </tbody> {% endfor %}
update 2:
context = { "queryset": queryset, "title": "list" } {% bid in queryset %} <tbody> <tr> <td>{{bid.user}}</td> <td>{{bid.amount}}</td> <td>{{bid.rank}}</td> </tr> </tbody>
in template, have looped through queryset , set rank each object.
for bid in queryset: # set bid.rank context = {...} return render(request, 'bid_list.html', context)
in template context, need pass queryset. don't include 'bid.rank'
- it's not possible have dot in template variable, , want rank every object, not current_rank
.
context = { "object_list": queryset, "title": "list" }
then, when loop through objects in queryset, can rank accessing rank
attribute.
{% obj in object_list %} {{ obj.user }} {{ obj.rank }} {% endfor %}
you might find less confusing if used same variable names in view , template - make more complicated switching queryset
, bid
object_list
, obj
.
context = { "queryset": queryset, "title": "list" } {% bid in queryset %} {{ bid.user }} {{ bid.rank }} {% endfor %}
Comments
Post a Comment