B
B
borisovdenis2017-08-17 09:42:25
Django
borisovdenis, 2017-08-17 09:42:25

How to disable username from user in django model?

For our project, it was necessary to override the user model and add some fields and get rid of some. We need to get rid of the username, because we want to do registration and authorization by mail. Authentication has already been rewritten - it works! The user enters by mail and password, everything is fine. But at registration the following error takes off.

AttributeError: 'AnonymousUser' object has no attribute 'email'

And if we want to update the user's data, then errors like the username field cannot be empty, etc. take off.
This is what the augmented user model looks like:
class CustomUser(AbstractUser, UpdateMixin):
    """
        Extension of standard user model.
        Added:
        --- phone number
        --- avatar
        --- chat_id
    """
    first_name = models.CharField(max_length=30, blank=False, validators=[validate_not_empty_filed])
    last_name = models.CharField(max_length=30, blank=False, validators=[validate_not_empty_filed])
    email = models.EmailField(blank=False, unique=True, validators=[validate_email_field])
    avatar = models.ImageField(upload_to='users_avatars/', blank=True, max_length=1000)
    # телефон хранится в формате +7*********
    phone = models.CharField(max_length=12, blank=True, validators=[validate_phone_field])
    # id чата с ботом в телеграме
    chat_id = models.CharField(max_length=15, blank=True, validators=[validate_telegram_chat_id_field])

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name']

    class Meta:
        managed = True

    # дальше идут методы модели

Question: how to deactivate username?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2017-08-24
@pyHammer

Now in any new project I put my own account application in which I changed USERNAME_FIELD to email and in settings I prescribe AUTH_USER_MODEL = 'account.User'. This eliminates problems with scaling, since it is difficult to attach or change authorization to an already existing project. I always get rid of this field if possible in favor of email, but if I need to leave it, I still use email for authorization. If interested, I can put this application on github

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question