Search code examples
djangodjango-authentication

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. 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?


Solution

  • You can't use parentheses in the {% if %} template tag. 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.

    {% 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).

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

    Django discourages putting complicated logic in the template. 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 %}