Search code examples
pythondjangorestdjango-rest-frameworkdjango-rest-auth

AttributeError when using custom UserDetailsSerializer in django-rest-auth


We have created a custom UserDetailsSerializer but when trying to run the application we get the error:

AttributeError: module 'path.to.serializers' has no attribute 'MPUserDetailsSerializer'

The full error is pasted here.

The setup for REST_AUTH_SERIALIZERS and USER_DETAILS_SERIALIZER in the django settings is:

REST_AUTH_SERIALIZERS = {
    'LOGIN_SERIALIZER': 'questions.serializers.LoginSerializer',
    'JWT_SERIALIZER' : 'questions.serializers.JWTSerializer',
    'USER_DETAILS_SERIALIZER' : 'questions.serializers.MPUserDetailsSerializer',
}

The custom serializer is:

from rest_auth import serializers as auth_serializers

class MPUserDetailsSerializer(auth_serializers.UserDetailsSerializer):
"""
User model w/o password
"""
class Meta:
    model = User
    fields = ('pk', 'username', 'email', 'name')
    read_only_fields = ('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

The workaround that we did was to remove the following lines from our local virtualenv, in the file /lib/python3.5/site-packages/rest-auth/serializers.py:

# Required to allow using custom USER_DETAILS_SERIALIZER  in
# JWTSerializer. Defining it here to avoid circular imports
rest_auth_serializers = getattr(settings, 'REST_AUTH_SERIALIZERS', {})
JWTUserDetailsSerializer = import_callable(
  rest_auth_serializers.get('USER_DETAILS_SERIALIZER', UserDetailsSerializer)
)

And replacing JWTUserDetailsSerializer with UserDetailsSerializer in the same file.

I know it's not a good practice to change third parties code and it doesn't make any sense to remove specifically the lines that are told to be required to allow custom USER_DETAILS_SERIALIZER, but we don't know whatelse to do to make it work, are we missing something? a config maybe?

We're using django v1.10.1, djangorestframework v3.4.7 and django-rest-auth v0.9.0


Solution

  • It was an issue from django-rest-auth fixed in the latest version - 0.9.1

    To see more, check this issue.