【问题标题】:Django: unable to make a calculation inside a templateDjango:无法在模板内进行计算
【发布时间】:2021-09-26 08:03:14
【问题描述】:

我已经创建了一个电子商务 Django 应用程序,并且在这个应用程序的后台,我有一个应该显示一些统计数据的页面。 我试图展示收益或损失。 对于成本,我在模型中创建了一个@property,如下所示:

class Statistics(models.Model):
    """
    The Statistics model represents the statistics that can be calculated
    """
    costs_infra = models.FloatField(verbose_name="Costs Infrastructure")
    costs_salary = models.FloatField(verbose_name="Costs Salary")

    class Meta:
        verbose_name_plural = "Statistics"   

    def __str__(self):
        """Unicode representation of Statistics"""

        return " Infra costs: {}, Salary costs: {}".format(
                self.costs_infra,
                self.costs_salary
            )
    
    @property
    def calculate_costs(self):
        return self.costs_infra + self.costs_salary

对于总收入,我在一个视图中计算如下:

@group_required('Administrator', 'Manager')
def stats_home(request):

    total_users = User.objects.all().count()
    costs = Statistics.objects.all()
    subscriptions_1month = Subscription.objects.get(plan_name='1 Month')
    subscriptions_1year = Subscription.objects.get(plan_name='1 Year')
    subscriptions_3year = Subscription.objects.get(plan_name='3 Years')
    user_subscriptions_1month = UserSubscription.objects.filter(subscription=subscriptions_1month).annotate(Count('user', distinct=True)).count()
    user_subscriptions_1year = UserSubscription.objects.filter(subscription=subscriptions_1year).annotate(Count('user', distinct=True)).count()
    user_subscriptions_3years = UserSubscription.objects.filter(subscription=subscriptions_3year).annotate(Count('user', distinct=True)).count()

    income_per_subscription_1month = Subscription.objects.get(plan_name='1 Month').price * UserSubscription.objects.filter(subscription=subscriptions_1month).count()
    income_per_subscription_1year = Subscription.objects.get(plan_name='1 Year').price * UserSubscription.objects.filter(subscription=subscriptions_1year).count()
    income_per_subscription_3years = Subscription.objects.get(plan_name='3 Years').price * UserSubscription.objects.filter(subscription=subscriptions_3year).count()
    
    total_income = income_per_subscription_1month + income_per_subscription_1year + income_per_subscription_3years

    return render (request, "stats_home.html", locals())

最后,我正在尝试进行一个简单的计算(总收入 - 总成本),但我无法在模板中执行此操作,据我所知,我的研究引导了我。

{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load has_group %}

{% block title %} Statistics Home {% endblock %}

{% block content %}

    <div class="card border-dark mb-4" id="profil">
        <h5 class="card-header bg-dark text-white">Total number of users subscribed to the site:</h5>
        <div class="card-body">
         {{total_users}}
        </div>
    </div>

    <div class="card border-dark mb-4" id="profil">
        <h5 class="card-header bg-dark text-white">Total number of users per subscription type:</h5>
        <div class="card-body">
        <br>1 Month: {{user_subscriptions_1month}}
        <br>1 Year: {{user_subscriptions_1year}}
        <br>3 Years: {{user_subscriptions_3years}}
        </div>
    </div>

    <div class="card border-dark mb-4" id="profil">
        <h5 class="card-header bg-dark text-white">Costs:</h5>
        <div class="card-body">
            {% for cost in costs %}
            <p>Infrastructure Costs: {{cost.costs_infra}}</p>
            <p>Salary Costs: {{cost.costs_salary}}</p>
            <p>Total Costs: {{cost.calculate_costs}}</p>
            {% endfor %}
        </div>
    </div>

    <div class="card border-dark mb-4" id="profil">
        <h5 class="card-header bg-dark text-white">  Total Income: </h5>
        <div class="card-body">
          {{total_income}}
        </div>
    </div>

    <div class="card border-dark mb-4" id="profil">
        <h5 class="card-header bg-dark text-white">  Benefits/Loss: </h5>
        <div class="card-body">
            Benefits/Loss: {{total_income - cost.calculate_costs}}
        </div>
    </div>

通过执行 {{total_income - cost.calculate_costs}} 我得到一个错误

无法解析余数:“total_income - cost.calculate_costs”中的“-cost.calculate_costs”

问题是我可以使用 {{cost.calculate_costs}} 获得总成本,使用 {{total_income}} 获得总收入,但不知何故我无法在模板内进行简单的减法。

实现这一目标的最佳方法是什么?

【问题讨论】:

  • 请添加您为模板尝试的代码和您得到的结果
  • 我已经尝试了以下许多其他方法(省略了 html): 收益/损失:{{total_income - cost.calculate_costs}} 我可以使用 {{cost. calculate_costs}} 和总收入 {{total_income}}
  • 我们需要看看你如何在你的 html 代码中集成所有的东西
  • 您应该相应地编辑您的第一篇文章,并添加相关视图;-)

标签: django django-models django-views django-templates


【解决方案1】:

您的问题是您试图在循环{% for cost in costs %} 之外访问cost.calculate_costs。由于未声明 cost,因此您会收到此错误。最重要的是,django 本身并不支持模板中的计算——原因是最好将逻辑完全保留在视图中,而只在模板中保留演示文稿。不过有addition filter,但还是需要计算total_costs

您的解决方案是在视图中计算total_profit

def stats_home(request):
    ...
    total_costs = sum(cost.calculate_costs for cost in costs)
    total_profit = total_income - total_costs

    return render (request, "stats_home.html", locals())
<div class="card border-dark mb-4" id="profil">
    <h5 class="card-header bg-dark text-white"> Benefits/Loss: </h5>
    <div class="card-body">
        Benefits/Loss: {{ total_profit }}
    </div>
</div>

【讨论】:

  • 这成功了,我确实缺少的是循环。非常感谢,已经解决了。
【解决方案2】:

您可以做的最好的事情是,不要在模板中进行计算,而是在视图中进行,因为它建议不要在模板中这样做,因为它会降低性能 网站的改为:

views.py

variable = total_income - total_costs
context = {"variable":variable}
return render(request, "stats_home.html", locals(), context)

【讨论】:

  • 我虽然想到了这个,但我的问题是我的 total_costs 是由模型上的 @property 计算的,所以不知何故我无法在我的视图中获得 total_costs(或者至少我没有还找到了一种方法)
  • 看到这个可能会有所帮助:stackoverflow.com/questions/45541874/…
  • 添加该序列化程序
  • 您可以在视图本身中进行计算,而不是使用属性...
猜你喜欢
  • 2011-08-16
  • 1970-01-01
  • 1970-01-01
  • 2021-03-19
  • 2017-10-19
  • 2011-09-11
  • 2018-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多