简体   繁体   English

Django检查登录的用户是否是创建记录的用户

[英]Django check if the user that is logged in is the user that created a record

I have a Django model that records the user who created a record. 我有一个Django模型来记录创建记录的用户。 I want to display a button on a template only if the user logged in is the same as the user on the record. 仅当登录的用户与记录中的用户相同时,我才想在模板上显示按钮。

I want to do something similar to: 我想做类似的事情:

{% if user.is_authenticated and (request.user.is_superuser or request.user == task.user) %}

where task is the record. 任务在哪里记录。

How can I do this? 我怎样才能做到这一点?

You can't use parentheses in the {% if %} template tag. 您不能在{% if %}模板标记中使用括号。 You can use the following check which is equivalent: 您可以使用以下等同的检查:

{% if user.is_authenticated and request.user.is_superuser or user.is_authenticated and request.user == task.user %}

You can then drop the first user.is_authenticated check, because only an authenticated user will be a superuser. 然后,您可以删除第一个user.is_authenticated检查,因为只有经过身份验证的用户才能成为超级用户。

{% if user.is_authenticated and request.user.is_superuser or user.is_authenticated and request.user == task.user %}

You may also be able to drop the second user.is_authenticated check if all tasks have a user (since an anonymous user is never equal to a real user). 您也可以删除第二个用户user.is_authenticated检查所有任务是否都有用户(因为匿名用户永远不等于真实用户)。

{% if request.user.is_superuser or request.user == task.user %}

Django discourages putting complicated logic in the template. Django不鼓励在模板中添加复杂的逻辑。 In this case, you might be able to put the logic in a filter, and then your template would simplify to: 在这种情况下,您可以将逻辑放入过滤器中,然后您的模板将简化为:

{% if task|display_button:request.user %}...{% endif %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM