【问题标题】:How to set permissions for users如何为用户设置权限
【发布时间】:2019-07-25 09:03:19
【问题描述】:

我正在尝试为我的 django 项目的用户设置权限。 我想要实现的是:

  • 用户在登录时应该只能查看/更新他的信息

  • 未登录的用户应该能够创建新用户

我的代码如下。

序列化器.py

from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password


class UserSerializer(serializers.HyperlinkedModelSerializer):
    password = serializers.CharField(max_length=128, style={'input_type': 'password'}, write_only=True)

    class Meta:
        model = User
        fields = ('url', 'id', 'username', 'email', 'first_name', 'last_name', 'password')

        def create(self, validated_data):
            username = validated_data['username']
            email = validated_data['email']
            first_name = validated_data['first_name']
            last_name = validated_data['last_name']
            password = make_password(validated_data['password'])

        def update(self, instance, validated_data):
            instance.email = validated_data.get('email', instance.email)
            instance.username = validated_data.get('username', instance.username)
            instance.first_name = validated_data.get('first_name', instance.first_name)
            instance.last_name = validated_data.get('last_name', instance.last_name)
            instance.password = make_password(validated_data.get('password', instance.password))
            instance.save()
            return instance

views.py

from urllib import request
from rest_framework import viewsets, status
from django.contrib.auth.models import User
from atest.serializers import UserSerializer
from rest_framework import permissions
from atest.permissions import IsOwnerOrReadOnly
from rest_framework.decorators import action
from rest_framework.response import Response


class UserViewSet(viewsets.ModelViewSet):
    """
    This viewset provides operations on Users table to the same user.
    """

    permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
    queryset = User.objects.all()
    serializer_class = UserSerializer

和权限.py

from rest_framework import permissions


class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    Custom permission to only allow owners of an object to edit it.
    """

    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.
        if request.method in permissions.SAFE_METHODS:
            return True

        # Write permissions are only allowed to the owner of the snippet.
        return obj.username == request.user

我能够成功登录。但是当我打开个人用户页面时,即

http://localhost:8000/users/8/

我无法执行 put、patch、delete 方法

【问题讨论】:

  • 你应该看看 Django 如何管理用户权限。通常,每个模型上的每个 CRUD 操作都有一个 Permission 对象。组基本上是用户可以关联的权限的集合,因此具有与他们关联的组的所有权限。查看docsthis article 了解更多信息。

标签: python django python-3.x django-rest-framework django-permissions


【解决方案1】:

试试这个权限类

# permissions.py
from rest_framework.permissions import BasePermission


class MyCustomPermissionClass(BasePermission):
    def has_permission(self, request, view):
        """
        You need to allow everyone to access the "list,create" apis. So, you should return "True" always
        """
        return True

    def has_object_permission(self, request, view, obj):
        return request.user == obj  # here "obj" will be the "User" instance


# views.py
class UserViewSet(viewsets.ModelViewSet):
    permission_classes = [MyCustomPermissionClass, ] 
    queryset = User.objects.all()
    serializer_class = UserSerializer

【讨论】:

    猜你喜欢
    • 2021-02-12
    • 2015-08-01
    • 1970-01-01
    • 2016-04-19
    • 2016-10-18
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2018-12-10
    相关资源
    最近更新 更多