django restframework创建用户和更新用户密码
如果我们需要做一个用户相关的API,我们可以用django的auth里的User model,并且增加user相关的serializer和viewset来实现。
以这种方式确实可以做出user相关的api,并且也可以通过api获取到用户的信息。但是会发现在创建新用户后,无法用对应的用户名和密码登录,在db中会看到该新增用户的password字段为空。也即是说get和delete操作可行,但post和put和patch的操作未达成效果。
比如我们先做一个出来。
在serializer里可以是:
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["id", "username", "email", "is_active", "is_staff", "is_superuser", "groups", "last_login", "user_permissions"]
在views中可以是:
from django.contrib.auth.models import User
from rest_framework import viewsets
from .serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
get:
Return all users.
post:
Create a new user.
put:
Update a user.
patch:
Update one or more fields on an existing user.
delete:
Delete existing user.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
filter_backends = [filters.SearchFilter]
search_fields = ["username", "email"]
我们会看到没有定义password字段在serializer中,但是我们也不能在api请求时把password也展示出来,于是需要设定为只写不可读,并且需要修改默认的create和update的方法。如下:
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["id", "username", "email", "password", "is_active", "is_staff", "is_superuser", "groups", "last_login"]
extra_kwargs = {"password": {"write_only": True}}
def create(self, validated_data):
user = get_user_model().objects.create_user(**validated_data)
return user
def update(self, instance, validated_data):
if "password" in validated_data:
password = validated_data.pop("password")
instance.set_password(password)
return super(UserSerializer, self).update(instance, validated_data)
此时便可正常创建用户,可以登录,也可以更新密码了。
下一篇:
PMP知识点(七)项目进度管理
上一篇:
PMP知识点(六)项目范围管理