Как ограничить просмотр в Django от других пользователей?

I am trying to make a page that only can be seen by the user for who the results belongs to. So I like to make that only the user with user_name_id=1 (and the superuser) could see the page that is localhost:8000/mpa/sum/1/

Я попробовал в html следующее:

{% if request.user.is_superuser %}
    <div class="container text-justify p-5">
        <div class="display-4 text-left text-primary my-3">
            ...
{% else %}
You are not able to view this page!
{% endif %}

Это отлично работает с суперпользователем, но как я могу сделать это с пользователями?

views.py

@login_required
def individual_sum(request, user_name_id):

... lots of query


context = {
    ... lots of contexts
}

return render(request, 'stressz/individual_sum.html', context) 

models.py

class IndividualSum_text(models.Model):

    def __str__(self):
        return str(self.user_name)

    user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
    ...integerfields and textfields here

Вы должны проверить, совпадает ли user_name_id с именем пользователя, или вошедший пользователь является суперпользователем:

from django.core.exceptions import PermissionDenied

@login_required
def individual_sum(request, user_name_id):
    if user_name_id != request.user.pk and not request.user.is_superuser:
        raise PermissionDenied
    # lots of query …
    # lots of contexts …
    return render(request, 'stressz/individual_sum.html', context)

в представлении вы должны отфильтровать записи так, чтобы они принадлежали пользователю с заданным user_name_id, поэтому если вам нужно получить IndividualSum_text объектов, вы работаете с:

IndividualSum_text.objects.filter(user_name_id=user_name_id)
Вернуться на верх