【问题标题】:How to restrict view in Django from other users?如何限制其他用户在 Django 中查看?
【发布时间】:2021-10-27 21:39:21
【问题描述】:

我正在尝试制作一个只有结果所属的用户才能看到的页面。所以我想让只有user_name_id=1(和超级用户)的用户才能看到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

【问题讨论】:

    标签: python django view user-permissions restriction


    【解决方案1】:

    您应该检查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(<strong>user_name_id=user_name_id</strong>)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 2015-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-21
      相关资源
      最近更新 更多