如何为用户设置权限

时间:2019-03-04 04:32:44

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

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

  • 用户登录后应该只能查看/更新其信息

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

我的代码如下。

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

和Permissions.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方法

1 个答案:

答案 0 :(得分:2)

尝试此权限类别

# 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