1、创建模型,user模型之前创建过了,继承了原有的模型类
2、序列化器
在 users/serializers.py 模块中添加:
class UserSerializer(serializers.ModelSerializer):class Meta:model = Userfields = ['id', 'username', 'password', 'mobile', 'email', 'is_staff', 'is_active', 'is_superuser']extra_kwargs = {'password': {'write_only': True} # 展示的时候不渲染密码}}def create(self, validated_data):user = super().create(validated_data)# 手动的处理密码user.set_password(validated_data['password'])user.save() # 不能忘记return userdef update(self, instance, validated_data):# 首先执行父类的updatesuper().update(instance, validated_data)# 判断是否有password过来password = validated_data.get('password')if password is not None:instance.set_password(password)instance.save() # 不要忘记了savereturn instance
3、创建视图
class UserViewSet(viewsets.ModelViewSet):serializer_class = UserSerializerqueryset = User.objects.all().order_by('-date_joined') # 按创建时间倒序permission_classes = [OnlySuperUser]
4、添加urls
router = DefaultRouter()
router.register('users', views.UserViewSet)
urlpatterns = [
...
path('', include(router.urls))
]
另外还有添加一个权限模块。
根目录下创建utils文件夹,存放基础模块,公共模块
编写自定义权限类 OnlySuperUser 实现只有超级管理员才可
以访问用户:
from rest_framework.permissions import BasePermissionclass OnlySuperUser(BasePermission):"""Allows access only to super users."""def has_permission(self, request, view):return bool(request.user and request.user.is_superuser)
最后还要