【问题标题】:Django: extra_content for class based view not displaying any dataDjango:基于类的视图的extra_content不显示任何数据
【发布时间】:2021-05-01 14:44:18
【问题描述】:

我正在尝试创建一个显示“案例”中所有项目的网站,并且我想在顶部显示“案例”中所有项目的总值。要获得这个数字,您将获得箱子中的所有物品,将它们的价值和数量相乘,然后将它们全部加起来。但是,当我将此传递给我的 extra_content 时,什么都没有显示。任何帮助都会很棒!

我的观点:

class CaseHome(ListView):
    model = CaseItem
    template_name = 'mycase/casehome.html'
    total = CaseItem.objects.all().aggregate(total=Sum(F('Item_Price')*F('Item_Quantity')))['total']
    extra_content = {'my_total': total}

我的模特:

class CaseItem(models.Model):
    Item_Title = models.CharField(max_length=200)
    Item_Price = models.DecimalField(default=0, max_digits=10, decimal_places=2)
    Item_Quantity = models.DecimalField(default=0, max_digits=10, decimal_places=2)

    def __str__(self):
        return self.Item_Title + ' | ' + str(self.Item_Quantity) + ' * $' + str(self.Item_Price)

    def get_absolute_url(self):
        return reverse('home')

我的模板:

{% block content %}
    <p>{{my_total}}</p>
    {% for item in object_list %}
        <div class="container">
            <div class="item" style="border: 2px solid black; margin: 3px; padding: 3px">
                <a href="{% url 'item-editor' item.pk %} "><h3 style="display: inline-block">{{ item.Item_Title }}</h3><h5 style="float: right"><span class="badge bg-info text-dark">Quantity:{{ item.Item_Quantity}}</span> <span class="badge bg-info text-dark" style="margin-left: 15px;"> Price: ${{item.Item_Price}} </span>
            </div>
            </h5></a>
            <hr>
        </div>
    {% endfor %}
{% endblock %}

【问题讨论】:

  • 你需要设置extra_context而不是extra_content
  • @IainShelvington 掌心。不过,快速问题是,使用extra_context 是一种常见/正确的做法还是更像是一种边缘情况?
  • 您使用它的方式有问题,我建议您改用 get_context_data 方法。 total 是在类上定义的,当数据发生变化时不会动态更新,您必须重新启动应用程序才能更新当前的值。我已经看到它更频繁地用作在 url 配置中传递的参数(作为 as_view 的参数),作为一种通过一些自定义重用相同视图但用于静态值的方式
  • @IainShelvington 我将如何处理get_context_data
  • 添加了一个例子的答案

标签: python python-3.x django django-models django-views


【解决方案1】:

您应该改写get_context_data。在类上定义total意味着当数据发生变化时它不会更新它只在应用程序启动时执行一次,您应该在每个请求上执行查询以获取最新数据

class CaseHome(ListView):
    model = CaseItem
    template_name = 'mycase/casehome.html'

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['my_total'] = CaseItem.objects.all().aggregate(total=Sum(F('Item_Price')*F('Item_Quantity')))['total']
        return context

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-04
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    相关资源
    最近更新 更多