Django 模板中的 for 循环内的布尔检查
Boolean check inside a for loop in a Django template
在 Django 模板中,我有以下 for 循环
{% for document in documents %}
<li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li>
{% endfor %}
通过这个循环,我向用户展示了我应用程序的所有上传文件。
现在假设我只想向用户显示 he/she 已上传的文件。
我在变量中有当前用户{{ request.user }}
而且我还有一个用户在 {{ document.who_upload }}
中进行了第 i 次上传
我的问题是如何比较循环内的这两个变量以仅显示具有当前用户的 who_upload
字段的上传?
例如,我尝试了语法
{% if {{ request.user }} == {{ document.who_upload }} %}
{% endif %}
不过好像不行。
此检查的正确语法是什么?
谢谢!
这应该可以完成工作:
{% if request.user.username == document.who_upload.username %}
{% endif %}
但是您应该考虑在您的视图中执行此逻辑。这是假设您没有在其他任何地方遍历整个查询集。
views.py
========
from django.shortcuts import render
from .models import Document
def documents(request):
queryset = Document.objects.filter(who_upload=request.user)
return render(request, 'document_list.html', {
'documents': queryset
})
更好的选择是比较用户的主键,而不是比较用户对象,后者肯定会有所不同。
{% if request.user.pk == document.who_upload.pk %}
<span>You uploaded this file</span>
{% endif %}
在 Django 模板中,我有以下 for 循环
{% for document in documents %}
<li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li>
{% endfor %}
通过这个循环,我向用户展示了我应用程序的所有上传文件。
现在假设我只想向用户显示 he/she 已上传的文件。
我在变量中有当前用户{{ request.user }}
而且我还有一个用户在 {{ document.who_upload }}
我的问题是如何比较循环内的这两个变量以仅显示具有当前用户的 who_upload
字段的上传?
例如,我尝试了语法
{% if {{ request.user }} == {{ document.who_upload }} %}
{% endif %}
不过好像不行。
此检查的正确语法是什么?
谢谢!
这应该可以完成工作:
{% if request.user.username == document.who_upload.username %}
{% endif %}
但是您应该考虑在您的视图中执行此逻辑。这是假设您没有在其他任何地方遍历整个查询集。
views.py
========
from django.shortcuts import render
from .models import Document
def documents(request):
queryset = Document.objects.filter(who_upload=request.user)
return render(request, 'document_list.html', {
'documents': queryset
})
更好的选择是比较用户的主键,而不是比较用户对象,后者肯定会有所不同。
{% if request.user.pk == document.who_upload.pk %}
<span>You uploaded this file</span>
{% endif %}