【问题标题】:Rendering a custom tag with a foreign key into templates issues将带有外键的自定义标签呈现到模板问题中
【发布时间】:2021-03-17 16:09:20
【问题描述】:

您好,这是我正在使用的模型

从 django.db 导入模型 从 users.models 导入 CustomUser

class Project(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(CustomUser, on_delete=models.PROTECT, editable=False)
    name = models.CharField(max_length=20, editable=False)
    total = models.DecimalField(max_digits=6, decimal_places=2, editable=False)
    created = models.DateTimeField(auto_now_add=True, editable=False, null=False, blank=False)
        
    def __str__(self):
        return self.name

该类由使用此视图的 HTML 表单填充:

def homepage(request):
if request.method == "POST":
    project = Project()
    name = request.POST.get('name')
    total = request.POST.get('total')
    created = datetime.datetime.now()
    user = request.user
    project.user = user
    project.name = name
    project.total = total
    project.created = created
    project.save()
    
    #return HttpResponse(reverse("homepage.views.homepage"))
    return render(request, 'homepage.html')
else:

    return render(request, 'homepage.html')

所以我在我的应用程序中添加了一个自定义标签,这是一个函数

@register.filter
def monthlyTotal(user):
    this_month = now().month
    return Project.objects.filter(
        created__month=this_month,
        user=user
        ).aggregate(
        sum_total=Sum('total')
        )['sum_total']

我在模板中这样调用标签

 <p>Total monthly sales = {{ user.username|monthlyTotal }}</p>

但是我收到一条错误消息,提示字段 ID 需要一个数字,但得到了“大师”,这是我的测试用户的名称,他有多个项目对象。如果我切换到 user.id,我没有收到错误,但它显示 None 哪个这是有道理的,因为当我在管理员中查看我的项目部分时,字段用户由用户名而不是 id 填充,因此不会有 user=id

的项目

【问题讨论】:

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


    【解决方案1】:

    你需要使用user,而不是用户名,所以:

    &lt;p&gt;Total monthly sales = {{ <b>user</b>|monthlyTotal }}&lt;/p&gt;

    【讨论】:

    • 感谢您的回答,这会产生与 user.id 相同的结果,它会导致 None 但登录的用户有多个项目,因此它应该计算出......奇怪。
    • @ThiMar:如果是None,则表示没有记录。没有记录的Sum 不是0,而是None 以区分例如0+0 和无元素之和。所以对于 那个 用户,this_month 没有 Project
    • @ThiMar:请注意,如果您使用 MySQL 并且在设置中使用 USE_TZ = True,则需要将时区信息添加到数据库中。有时这不是自动完成的,然后过滤“无法正常工作”。见django-antipatterns.com/troubleshooting/…
    • 天哪!这是我上周末进行测试时的人为错误!所以十一月。非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 2011-01-02
    • 1970-01-01
    相关资源
    最近更新 更多