如何在django模板中增加计数器

k2arahey  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(144)

我正在尝试获取每个侵权者的侵权总数。计数器未递增。({{ a| add:“1”}})它输出1 1 1而不是总共3。请协助。

{% for infringer in page_obj %}   
<tr>   
 <td>{{infringer.id}}</td>  
 <td>{{infringer.created|date:"d M, Y"}}</td>  
 <td>{{infringer.name}}</td>   
 <td>{{infringer.brand_name}}</td>  
 <td>{{infringer.status}}</td>   
 <td>   
{% with a=0 %}

  {% for i in inc %}   
     {% if infringer.id == i.infringer.id %}
        {{ a|add:"1" }}

      {% endif %}
  {% endfor %}    
{% endwith %}

views.py

@login_required(login_url='login') 
def infringerlist(request):
   q = request.GET.get('q') if request.GET.get('q') != None else '' 
   ings= Infringer.objects.filter(Q(created__icontains=q) | Q(id__icontains=q) | 
   Q(status__name__icontains=q) |
   Q(brand_name__icontains=q) | Q(name__icontains=q),
customer=request.user.customer,)
paginator = Paginator(ings, 10)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
inc = Infringement.objects.filter(customer=request.user.customer)
   context= {'page_obj': page_obj, 'inc': inc}
   return render(request,'base/infringers_list.html', context)
4smxwvx5

4smxwvx51#

模板 * 不 * 应该有业务逻辑。它们也不应该改变状态。它们应该只是 * 呈现 * 数据。
您可以计算入侵的数量,然后将其传递给上下文:

@login_required(login_url='login')
def infringerlist(request):
    q = request.GET.get('q') if request.GET.get('q') != None else ''
    ings = Infringer.objects.filter(
        Q(created__icontains=q)
        | Q(id__icontains=q)
        | Q(status__name__icontains=q)
        | Q(brand_name__icontains=q)
        | Q(name__icontains=q),
        customer__user=request.user,
    )
    paginator = Paginator(ings, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    infrigments = Infringement.objects.filter(customer__user=request.user).count()
    return render(
        request,
        'base/infringers_list.html',
        context={'page_obj': page_obj, 'infrigments': infrigments},
    )

并使用{{ infrigments }}对其进行渲染。

相关问题