我有一个Schedule
用字段调用的类(这是正确的吗?)我使用
admins = models.ManyToManyField(User)
. 此字段包含我可以选择多个用户的列表。
在时间表视图中,我显示了一堆信息。我想根据当前登录的用户是否包含在正在查看的时间表的管理员中来显示一些额外的内容。
According to Django philosophy, you should have your business logic within views and presentation logic in the template. So the computation if the logged user is among the admins should be done in a view, and if the user is, then what is displayed should be determined in the template. You can accomplish that by:
# views.py
def schedule(request, id):
schedule = get_object_or_404(Schedule, pk=id)
if request.user.is_authenticated():
is_admin = schedule.admins.filter(pk=schedule.pk).exists()
else:
is_admin = False
data = {
'schedule': schedule,
'is_admin': is_admin,
}
return render_to_response('template.html', data)
# template.html
{% if is_admin %}
<p>You are an admin of the schedule!</p>
{% else %}
<p>Sorry. You are not an admin of the schedule</p>
{% endif %}