django 如何在rest-auth的注册端点添加额外字段

i2loujxw  于 2023-10-21  发布在  Go
关注(0)|答案(2)|浏览(94)

我正在使用rest-auth注册API进行用户注册。我在UserProfile模型中有一些额外的字段。

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    org_id = models.CharField(max_length=100, default='')
    is_teacher = models.BooleanField(blank=True, default=False)

    def __str__(self):
        return self.user.username

    def create_profile(sender, **kwargs):
        if kwargs['created']:
            user_profile = UserProfile.objects.create(user=kwargs['instance'])

    post_save.connect(create_profile, sender=User)

UserProfile模型如上所示。如何将这些字段添加到rest-auth注册API端点并将数据保存到数据库。

ulydmbyx

ulydmbyx1#

我为自己找到了答案
序列化程序可以写成

from rest_framework import serializers
from rest_auth.registration.serializers import RegisterSerializer
from .models import UserProfile


class RegistrationSerializer(RegisterSerializer):

    first_name = serializers.CharField(required=False)
    last_name = serializers.CharField(required=False)
    personal_id = serializers.CharField(required=True)

    def custom_signup(self, request, user):
        user.first_name = self.validated_data.get('first_name', '')
        user.last_name = self.validated_data.get('last_name', '')
        user.userprofile.personal_id = self.validated_data.get(
            'personal_id', '')

        user.save(update_fields=['first_name', 'last_name'])
        user.userprofile.save(update_fields=['org_id'])

我没有添加is_teacher,因为它是可选的。
在views.py中,扩展rest_auth.regeistration.viewsRegisterView以传递此数据并完成。

class RegistrationView(RegisterView):
    serializer_class = RegistrationSerializer

最后添加一个url并传递RegisterView.as_view()

jjjwad0x

jjjwad0x2#

不需要更改RegisterView和URL模式。只需在www.example.com中添加settings.py:

REST_AUTH = {
    'REGISTER_SERIALIZER': 'my-app.serializers.RegistrationSerializer',
}

相关问题