【问题标题】:filter model queryset using with template tag使用模板标签过滤模型查询集
【发布时间】:2016-06-19 19:29:03
【问题描述】:

有没有办法将查询集过滤器与with 模板标签结合起来?

我正在尝试执行以下操作:

{% if request.user.is_superuser %}
   {% with arts=category.articles.all %}
{% else %}
   {% with arts=category.get_active_articles %}
{% endif %}
#other statements
   # Do some more template stuff in for loop

其他变体:

{% with arts=category.articles.all if self.request.user.is_superuser else category.get_active_articles %}

无法在模型中执行自定义查询集,因为我没有请求。

有没有办法获得我需要的过滤?我正在尝试为超级用户/员工和普通用户显示不同的查询集,这样我就可以对状态等进行一些更新,而无需转到管理页面。

【问题讨论】:

    标签: django django-models django-templates django-template-filters


    【解决方案1】:

    templates 中编写逻辑是一种不好的约定/做法。 Templates 应该传递数据,就是这样。在您的情况下,您可以在 views 中执行此操作。

    app/views.py

    from django.shortcuts import render
    from app.models import Category
    
    def articles(request):
        if request.user.is_superuser:
            articles = Category.articles.all()
        else:
            articles = Category.get_active_articles()
    
        context = {'articles': articles}
        return render(request, 'articles.html', context)
    

    app/templates/articles.html

    {% for a in articles %}
        {% a.title %}
        {% a.content %}
    {% endfor %}
    


    PS:阅读this以了解应该存在的内容。

    【讨论】:

      猜你喜欢
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 2020-04-02
      • 2013-03-05
      相关资源
      最近更新 更多