Skip to content
Advertisement

Field name `username` is not valid for model

I am attempting to use rest-auth supplied serialisers to GET (*with headers) user details from the defined endpoint /rest-auth/user/

(*with headers (Content-Type: application/json Authorization: Token 1a5472b2af03fc0e9de31fc0fc6dd81583087523 ))

I am getting the following traceback: https://dpaste.de/oYay#L

I have defined custom user model (using email rather than username)as such:

class UserManager(BaseUserManager):
def create_user(self, email, password, **kwargs):
    user = self.model(
        # lower-cases the host name of the email address
        # (everything right of the @) to avoid case clashes
        email=self.normalize_email(email),
        is_active=True,
        **kwargs
    )
    user.set_password(password)
    user.save(using=self._db)
    return user

def create_superuser(self, email, password, **kwargs):
    user = self.model(
        email=email,
        is_staff=True,
        is_superuser=True,
        is_active=True,
        **kwargs
    )
    user.set_password(password)
    user.save(using=self._db)
    return user


class MyUser(AbstractBaseUser, PermissionsMixin):
    USERNAME_FIELD = 'email'

    email = models.EmailField(unique=True)

Settings as follows:

AUTH_USER_MODEL = 'users.MyUser'
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
# Config to make the registration email only
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_EMAIL_VERIFICATION = 'optional'
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

Not sure how to go about correcting this error.. so that it complies with the rest-auth serialisers.

Advertisement

Answer

In django-rest-auth, there is a default serializer for User models :

    USER_DETAILS_SERIALIZER = 'rest_auth.views.UserDetailsView' 

And here they are serializing django.contrib.auth.User

In your case, you are using a custom user model and you don’t have a username field in your models, so it is giving an error while trying to serialize the field username. So you have to write a serializer for your User model and add a path to your settings:

example:

    class CustomUserDetailsSerializer(serializers.ModelSerializer):

        class Meta:
            model = MyUser
            fields = ('email',)
            read_only_fields = ('email',)

In settings.py

    USER_DETAILS_SERIALIZER = CustomUserDetailsSerializer 
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement