Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Removing username from user model

In order to create a new user model in Django 1.5.x, there are two approaches:

  1. Inherit AbstractUser class which is the default user model you get, this way you can extend it with any attributes you want. However, if you want to remove any field, it's technically possible but not recommended; even if it can be done, it is against OOP principles, I believe. So if you would like to alter the current user model, there is the second approach.
  2. Inherit AbstractBaseUser, which by looking at the code provides very basic functionality. You will miss all the goodness of permissions, profile retrieval and absolute url construction, unless you copy it from the default Django user model.

The above is my understanding of the situation. Correct me if I'm wrong, but doesn't this mean that if I want to simply remove the username field out of the model since I won't need it at all, I have to copy paste the model code provided in the framework and inherit from AbstractBaseUser and PermissionsMixin? For such a simple thing, this approach doesn't look very pretty to me, and it looks a bit odd since I'm quite certain the custom user model was introduced largely because of the popular use case of email field as the user identifier instead of username.

Your thoughts (and corrections) please.

like image 888
Aziz Alfoudari Avatar asked Nov 26 '22 20:11

Aziz Alfoudari


1 Answers

If You look at the source code of the django.contrib.auth.models file then you will see that definition of the AbstractUser class is rather short and starts like this:

class AbstractUser(AbstractBaseUser, PermissionsMixin):
    ...

It inherits from the AbstractBaseUser and PermissionMixin. You could define your custom model and also inherit it from the mentioned classes to get permissions support. If you want all other model fields then yes, you will need to copy them, but it's also an opportunity to customize things to match your needs.

like image 107
HankMoody Avatar answered Dec 10 '22 05:12

HankMoody