【问题标题】:How do you display a views.py's variable linked to annotated queryset in a django template?如何在 django 模板中显示链接到带注释查询集的 views.py 变量?
【发布时间】:2018-05-24 22:11:49
【问题描述】:

如何在 django 模板中显示链接到带注释查询集的 views.py 变量?我知道带注释的查询集在打印出来时会返回正确的数据,但不知何故,for 循环模板没有检索 html 页面上的数据。有人可以告诉我如何解决这个问题吗?谢谢。

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

ps = Pastry.objects.values('pastry').annotate(total=Count('pastry')) 这一行返回正确的数据:

{'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(模板)

{% 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 %}

【问题讨论】:

  • 你想在模板中检索变量的值还是不知道如何发送到模板?最重要的是,您在哪个视图中拥有该查询集?
  • 我将查询集作为变量。 ps = Pastry.objects.values('pastry').annotate(total=Count('pastry')) 我想在 Pastry_list.html 模板中检索这个。
  • 你在特定视图中使用它吗?
  • 我没有。我一定要吗?我把它放在什么类型的视图中?在不使用 {% url 'template' %} 的情况下如何从模板访问视图?
  • 当然,渲染模板的视图,通过get_context_data()方法发送变量

标签: python django django-templates


【解决方案1】:

更多信息可以在Documentation找到
基本上,您可以通过get_context_data() 方法将更多变量发送到模板

示例:

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

使用get_context-data(),您的变量ps 在模板pastry_list.html 中可用

【讨论】:

  • 谢谢你,这是解决它的答案。非常感谢您的快速回复。
猜你喜欢
  • 1970-01-01
  • 2020-05-14
  • 2020-09-10
  • 2019-02-19
  • 1970-01-01
  • 2023-03-07
  • 2012-05-28
  • 2020-04-29
  • 2021-10-03
相关资源
最近更新 更多