gpt4 book ai didi

python - Django Rest Framework 创建用户和用户配置文件

转载 作者:太空狗 更新时间:2023-10-29 22:18:36 27 4
gpt4 key购买 nike

我正在尝试创建将使用我的 API 创建新用户的 View 。我正在为我的用户使用自定义模型,并且还创建了一个名为 Profile 的模型来管理与身份验证无关的数据。

我是 Django 世界的新手,这可能相当困难。

这是我的模型.py

class UserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('User must have an email address')

user = self.model(
email = self.normalize_email(email),
)
user.set_password(password)
user.save()
return user

def create_superuser(self, email, password):
user = self.create_user(email, password=password)
user.is_admin = True
user.save()
return user


class User(AbstractBaseUser):
objects = UserManager()
email = models.EmailField(unique=True, db_index=True)
created = models.DateTimeField('created', auto_now_add=True)
modified = models.DateTimeField(auto_now=True)

is_active = models.BooleanField('active', default=True)
is_admin = models.BooleanField('admin', default=False)

USERNAME_FIELD = 'email'

ordering = ('created',)

def is_staff(self):
return self.is_admin

def has_perm(self, perm, obj=None):
return True

def has_module_perms(self, app_label):
return True

def get_short_name(self):
return self.email

def get_full_name(self):
return self.email

def __unicode__(self):
return self.email


class Profile(models.Model):
GENDER = (
('M', 'Homme'),
('F', 'Femme'),
)

user = models.OneToOneField(settings.AUTH_USER_MODEL)
first_name = models.CharField(max_length=120, blank=False)
last_name = models.CharField(max_length=120, blank=False)
gender = models.CharField(max_length=1, choices=GENDER)
zip_code = models.CharField(max_length=5, validators=[MinLengthValidator(5)], blank=False)

def __unicode__(self):
return u'Profile of user: {0}'.format(self.user.email)


def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
post_save.connect(create_profile, sender=User)


def delete_user(sender, instance=None, **kwargs):
try:
instance.user
except User.DoesNotExist:
pass
else:
instance.user.delete()
post_delete.connect(delete_user, sender=Profile)

这是我的serializers.py

class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ('first_name', 'last_name', 'gender', 'zip_code',)


class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer(required=True)
class Meta:
model = User
fields = ('url', 'email', 'profile', 'created',)

这是views.py

class UserList(generics.ListCreateAPIView):
permission_classes = (IsAuthenticatedOrWriteOnly,)
serializer_class = UserSerializer

def get_queryset(self):
if self.request.user.is_staff:
return User.objects.all()
else:
return self.request.user

def post(self, request, format=None):
serializer = ProfileSerializer(data=request.data)
print serializer.__dict__
if serializer.is_valid():
print "valid"
return Response("placeholder", status=status.HTTP_201_CREATED)

我的目标是能够同时创建用户和配置文件,同时能够验证所有内容,我该如何实现?

最佳答案

确实,Django Rest Framework 无法处理嵌套关系的这项工作,因此您必须自己实现这些方法。我将举例说明您的代码应该是什么样子。

您的观点:

class UserList(generics.ListCreateAPIView):
permission_classes = (IsAuthenticatedOrWriteOnly,)
serializer_class = UserSerializer

def post(self, request, format=None):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

现在,您的序列化器的save 方法将在您想要创建对象时调用create 方法,并在您需要时调用update 方法更新对象。因此,让我们实现 UserSerializercreate 方法,它将创建配置文件和用户。这是您的 UserSerializer 应该是什么样子的简单示例:

class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer(required=True)
class Meta:
model = User
fields = ('url', 'email', 'profile', 'created',)

def create(self, validated_data):

# create user
user = User.objects.create(
url = validated_data['url'],
email = validated_data['email'],
# etc ...
)

profile_data = validated_data.pop('profile')
# create profile
profile = Profile.objects.create(
user = user
first_name = profile_data['first_name'],
last_name = profile_data['last_name'],
# etc...
)

return user

正如我所说,这是一个例子,你必须完成它才能做你想做的事,但现在,你知道怎么做了:)要定义更新期间的行为,实现一个更新 方法。

关于python - Django Rest Framework 创建用户和用户配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33659994/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com