python - 如何为用户设置权限
问题描述
我正在尝试为我的 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
视图.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
我能够成功登录。但是当我打开个人用户页面时,即
我无法执行 put、patch、delete 方法
解决方案
试试这个权限类
# 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
推荐阅读
- html - 如何通过输入单选更改颜色 SVG?
- sql - 基于日期比较sql的列缺失值
- elasticsearch - Elastic Search 7.9:在多个字段上精确
- ios - Razorpay cordova 插件不适用于 iOS 卡在初始屏幕上
- reactjs - 在Visual Studio Code中更改React JS代码时如何使STS重新编译项目?
- mongodb - 使用 ref 值更新多个元素
- javascript - 用 span 一次性替换剩余的一组单词
- python - Django 渲染字典
- swagger - 如何在 swagger.yaml / openapi.yaml 文件中访问 AWS SAM 映射
- gradle - 配置“编译”已过时。替换为实现后给出错误