如何为用户设置权限
How to set permissions for users
我正在尝试为我的 django 项目的用户设置权限。
我想要实现的是:
用户登录后应该view/update只能查看他的信息
未登录用户应该可以创建新用户
我的代码如下。
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
我可以成功登录。但是当我打开个人用户页面时,即
我无法执行放置、修补、删除方法
试试这个权限class
# permissions.py
from rest_framework.permissions import BasePermission
<b>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</b>
# views.py
class UserViewSet(viewsets.ModelViewSet):
<b>permission_classes = [MyCustomPermissionClass, ] </b>
queryset = User.objects.all()
serializer_class = UserSerializer
我正在尝试为我的 django 项目的用户设置权限。 我想要实现的是:
用户登录后应该view/update只能查看他的信息
未登录用户应该可以创建新用户
我的代码如下。
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
我可以成功登录。但是当我打开个人用户页面时,即
我无法执行放置、修补、删除方法
试试这个权限class
# permissions.py
from rest_framework.permissions import BasePermission
<b>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</b>
# views.py
class UserViewSet(viewsets.ModelViewSet):
<b>permission_classes = [MyCustomPermissionClass, ] </b>
queryset = User.objects.all()
serializer_class = UserSerializer