Django 使用 Django Rest Framework 创建自定义用户
Django Creating a Custom User with the Django Rest Framework
我正在尝试使用 Django Rest Framework 创建自定义用户。我已经到了可以创建普通用户的地步,但我不确定如何将其扩展到自定义用户模型。
models.py:
from django.db import models
from django.contrib.postgres.fields import ArrayField
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
languages = ArrayField(models.CharField(max_length=30, blank=True))
serializers.py:
from rest_framework import serializers
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'username', 'password')
def create(self, validated_data, instance=None):
user = super(UserSerializer, self).create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
views.py:
@api_view(['POST'])
@permission_classes((AllowAny,))
def create_user(request):
serialized = UserSerializer(data=request.data)
if serialized.is_valid():
serialized.save()
return Response(serialized.data, status=status.HTTP_201_CREATED)
else:
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
如何将 languages
字段扩展到 UserSerializer
可以处理的地方?每次创建 user
时创建一个 signal
会更好,然后自动创建一个 userprofile
吗?
您可以通过两种方式实现,一种是创建配置文件序列化程序,另一种是不创建它。
使用序列化程序,
class UserProfileSerializer(serializers.ModelSerializer):
languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True))
class Meta:
model = UserProfile
fields = ('languages',)
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
userprofile = UserProfileSerializer(required=False)
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'username', 'password', 'userprofile')
def create(self, validated_data, instance=None):
profile_data = validated_data.pop('userprofile')
user = User.objects.create(**validated_data)
user.set_password(validated_data['password'])
user.save()
UserProfile.objects.update_or_create(user=user,**profile_data)
return user
没有配置文件序列化器
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True), source="userprofile.languages")
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'username', 'password', 'lanugages')
def create(self, validated_data, instance=None):
profile_data = validated_data.pop('userprofile')
user = User.objects.create(**validated_data)
user.set_password(validated_data['password'])
user.save()
UserProfile.objects.update_or_create(user=user,**profile_data)
return user
我正在尝试使用 Django Rest Framework 创建自定义用户。我已经到了可以创建普通用户的地步,但我不确定如何将其扩展到自定义用户模型。
models.py:
from django.db import models
from django.contrib.postgres.fields import ArrayField
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
languages = ArrayField(models.CharField(max_length=30, blank=True))
serializers.py:
from rest_framework import serializers
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'username', 'password')
def create(self, validated_data, instance=None):
user = super(UserSerializer, self).create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
views.py:
@api_view(['POST'])
@permission_classes((AllowAny,))
def create_user(request):
serialized = UserSerializer(data=request.data)
if serialized.is_valid():
serialized.save()
return Response(serialized.data, status=status.HTTP_201_CREATED)
else:
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
如何将 languages
字段扩展到 UserSerializer
可以处理的地方?每次创建 user
时创建一个 signal
会更好,然后自动创建一个 userprofile
吗?
您可以通过两种方式实现,一种是创建配置文件序列化程序,另一种是不创建它。 使用序列化程序,
class UserProfileSerializer(serializers.ModelSerializer):
languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True))
class Meta:
model = UserProfile
fields = ('languages',)
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
userprofile = UserProfileSerializer(required=False)
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'username', 'password', 'userprofile')
def create(self, validated_data, instance=None):
profile_data = validated_data.pop('userprofile')
user = User.objects.create(**validated_data)
user.set_password(validated_data['password'])
user.save()
UserProfile.objects.update_or_create(user=user,**profile_data)
return user
没有配置文件序列化器
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True), source="userprofile.languages")
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'username', 'password', 'lanugages')
def create(self, validated_data, instance=None):
profile_data = validated_data.pop('userprofile')
user = User.objects.create(**validated_data)
user.set_password(validated_data['password'])
user.save()
UserProfile.objects.update_or_create(user=user,**profile_data)
return user