Search code examples
pythondjangoviewuser-permissionsrestriction

How to restrict view in Django from other users?


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/

I tried in the html this:

{% 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 %}

This works fine with the superuser but how could I do this with the users?

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

Solution

  • You should check if the user_name_id is identical to that of the user, or the logged in user is a super user:

    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)

    in the view you should filter the entires such that these belong to the user with the given user_name_id, so if you need to retrieve IndividualSum_text objects, you work with:

    IndividualSum_text.objects.filter(user_name_id=user_name_id)