Django rest registration

2019-04-11 23:32发布

问题:

I am using Django-rest-auth (https://github.com/Tivix/django-rest-auth) in my django project for login and registration. I see a default registration form as follows:

Currently I am being able to register a new user with email instead of username. The default auth_user table in my MySql database has following columns: (id, password,last_login, is_superuser, username, first_name, last_name, email, is_staff, is_active, date_joined)

My settings.py :

INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'rest_framework',
#Rest-auth
'rest_framework.authtoken',
'rest_auth',
#Rest-auth registration
'allauth',
'allauth.account',
'rest_auth.registration',
#Following is added to allow cross domain requests i.e. for serving requests those are coming from frontend app 
'corsheaders',
'flights',
)

I want modify my registration form to have first name and last name with above fields so that when I register a new user, those two columns are also populated with first_name & last_name. Currently I have no additional view for registration nor any custom user model, I am simply using API endpoints provided by django-rest-auth.

How can I achieve this?

回答1:

You can achieve that by extending rest-auth's RegisterSerializer

from rest_auth.registration.serializers import RegisterSerializer

class RegistrationSerializer(RegisterSerializer):
    first_name = serializers.CharField(required=True)
    last_name = serializers.CharField(required=True)

    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', '')
        }

And on your settings.py add this:

REST_AUTH_REGISTER_SERIALIZERS = {
    'REGISTER_SERIALIZER': 'path.to.your.RegistrationSerializer'
}


回答2:

if you want add field, you must add them to serializer. Find in serializers.py RegisterSerializer and add there first_name and last_name

first_name = serializers.CharField(required=True, write_only=True)
last_name = serializers.CharField(required=True, write_only=True)

then add them to method in this serializer:

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', '')
    }

Hope this help you.