How do you display a views.py's variable linked to annotated queryset in a django template? I know the annotated queryset returns correct data when I printed it out, but somehow the template for loop is not retrieving the data on the html page. Can someone please advise me on how to fix this issue? Thanks.
VIEWS.PY
from django.shortcuts import render
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
from django.urls import reverse_lazy
from myapp.models import Pastry
from myapp.forms import PastryForm
from django.db.models import F
This line ps = Pastry.objects.values('pastry').annotate(total=Count('pastry'))
returns correct data:
{'pastry': 'Brownie', 'total': 1}
{'pastry': 'Cake', 'total': 1}
{'pastry': 'Cupcake', 'total': 1}
{'pastry': 'Fruit Tart', 'total': 1}
{'pastry': 'Muffin', 'total': 2}
class PollsListView(ListView):
model = Pastry
def get_queryset(self):
return Pastry.objects.all()
class PollsDetailView(DetailView):
model = Pastry
class PollsCreateView(CreateView):
success_url = reverse_lazy('pastry_list')
form_class = PastryForm
model = Pastry
class PollsUpdateView(UpdateView):
success_url = reverse_lazy('pastry_list')
form_class = PastryForm
model = Pastry
class PollsDeleteView(DeleteView):
model = Pastry
success_url = reverse_lazy('pastry_list')
pastry_list.html (template)
{% extends "base.html" %}
{% block content %}
<div class="jumbotron">
<a href="{% url 'pastry_new' %}">New Poll</a>
<h1>Voting for the favorite pastry</h1>
Somehow this code here is not displaying any data.
{% for p in ps %}
{% for k, v in p.items %}
{{k}}{{v}}
{% endfor %}
{% endfor %}
{% for pastry in pastry_list %}
<div class="pastry">
<h3><a href="{% url 'pastry_detail' pk=pastry.pk %}">
{{ pastry.pastry }}</a></h3>
</div>
{% endfor %}
</div>
{% endblock %}
More info can be found in the Documentation
Basically, you can send more variables to template via get_context_data()
method
Sample:
class PollsListView(ListView):
model = Pastry
def get_queryset(self):
return Pastry.objects.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['ps'] = = Pastry.objects.values('pastry').annotate(total=Count('pastry'))
return context
With get_context-data()
, your variable ps
is available in the template pastry_list.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.