Django rest-auth allauth registration with email, first and last name, and without username

anauzrmj  于 2022-12-14  发布在  Go
关注(0)|答案(4)|浏览(130)

我使用django-rest-auth和allauth来登录和注册我的django应用程序。我没有写任何额外的代码来登录或注册。注册成功,使用emailid和提供的密码。
我不使用用户名进行身份验证,而是使用电子邮件。
在我的可浏览的API注册我得到以下:

除了这些字段之外,我还想设置first_name和last_name(默认的auth_user表包含这些列),这样我新创建的auth_user也会设置这些字段以及email和散列密码。
如何实现这一点?这个可浏览的表单本身并不重要,但能够存储first_name和last_name是我主要需要的。

5gfr0r5j

5gfr0r5j1#

1.确保settings.py文件中包含ACCOUNT_USERNAME_REQUIRED = False
1.对于first_namelast_name,您需要编写一个自定义的RegisterSerializer(https://github.com/iMerica/dj-rest-auth/blob/bf 168 d9830 ca 2 e6 fde 56 f83 f46 fe 48 ab 0adc 8877/dj_rest_auth/注册/序列化器。py#L197)
下面是serializers.py示例代码

from allauth.account import app_settings as allauth_settings
from allauth.utils import email_address_exists
from allauth.account.adapter import get_adapter
from allauth.account.utils import setup_user_email

class RegisterSerializer(serializers.Serializer):
    first_name = serializers.CharField(required=True, write_only=True)
    last_name = serializers.CharField(required=True, write_only=True)
    email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED)
    password1 = serializers.CharField(write_only=True)
    password2 = serializers.CharField(write_only=True)

    def validate_username(self, username):
        username = get_adapter().clean_username(username)
        return username

    def validate_email(self, email):
        email = get_adapter().clean_email(email)
        if allauth_settings.UNIQUE_EMAIL:
            if email and email_address_exists(email):
                raise serializers.ValidationError(
                    _('A user is already registered with this e-mail address.'),
                )
        return email

    def validate_password1(self, password):
        return get_adapter().clean_password(password)

    def validate(self, data):
        if data['password1'] != data['password2']:
            raise serializers.ValidationError(_("The two password fields didn't match."))
        return data

    def custom_signup(self, request, user):
        pass

    def get_cleaned_data(self):
        return {
            'first_name': self.validated_data.get('first_name', ''),
            'last_name': self.validated_data.get('last_name', ''),
            'username': self.validated_data.get('username', ''),
            'password1': self.validated_data.get('password1', ''),
            'email': self.validated_data.get('email', ''),
        }

    def save(self, request):
        adapter = get_adapter()
        user = adapter.new_user(request)
        self.cleaned_data = self.get_cleaned_data()
        user = adapter.save_user(request, user, self, commit=False)
        if "password1" in self.cleaned_data:
            try:
                adapter.clean_password(self.cleaned_data['password1'], user=user)
            except DjangoValidationError as exc:
                raise serializers.ValidationError(
                    detail=serializers.as_serializer_error(exc)
            )
        user.save()
        self.custom_signup(request, user)
        setup_user_email(request, user, [])
        return user

1.在settings.py中,确保添加以引用新串行器。

REST_AUTH_REGISTER_SERIALIZERS = {
        'REGISTER_SERIALIZER': 'path.to.RegisterSerializer',
}
nkoocmlb

nkoocmlb2#

您也可以只覆盖RegisterSerializer上的custom_signup方法,该方法就是用于此目的的。

from rest_auth.registration.serializers import RegisterSerializer
from rest_auth.registration.views import RegisterView
from rest_framework import serializers

class NameRegistrationSerializer(RegisterSerializer):

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

  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.save(update_fields=['first_name', 'last_name'])

class NameRegistrationView(RegisterView):
  serializer_class = NameRegistrationSerializer

然后在urls.py中使用以下命令

url(r'^rest-auth/registration/name-registration/$', NameRegistrationView.as_view(), name="rest_name_register")

或在settings.py中设置REGISTER_SERIALIZER

REST_AUTH_REGISTER_SERIALIZERS = {
    'REGISTER_SERIALIZER': 'path.to.RegisterSerializer',
}
qyuhtwio

qyuhtwio3#

更好的解决方案是从RegisterSerializer继承并根据需要扩展。

class MyRegisterSerializer(RegisterSerializer):
    first_name = serializers.CharField(required=True, write_only=True)
    last_name = serializers.CharField(required=True, write_only=True)

    def get_cleaned_data(self):
        return {
            'first_name': self.validated_data.get('first_name', ''),
            'last_name': self.validated_data.get('last_name', ''),
            'password1': self.validated_data.get('password1', ''),
            'email': self.validated_data.get('email', ''),
        }

    def save(self, request):
        adapter = get_adapter()
        user = adapter.new_user(request)
        self.cleaned_data = self.get_cleaned_data()
        adapter.save_user(request, user, self)
        setup_user_email(request, user, [])
        user.save()
        return user
dnph8jn4

dnph8jn44#

对于任何需要快速解决方案的人

from dj_rest_auth.registration.serializers import RegisterSerializer
from rest_framework import serializers

class CustomRegistration(RegisterSerializer):
     first_name = serializers.CharField(write_only=True)
     last_name = serializers.CharField(write_only=True)
     def custom_signup(self, request, user):
         first = request.POST.get("first_name")
         last = request.POST.get("last_name")
         user.first_name = first
         user.last_name = last
         user.save()

'
确保在设置中包含自定义注册的路径:

REST_AUTH_REGISTER_SERIALIZERS = {
      'REGISTER_SERIALIZER': 'path_to.CustomRegistration',
}

相关问题