Using email as username field in Django 1.5 custom User model results in FieldError

前端 未结 4 1662
你的背包
你的背包 2020-12-15 05:06

I want to use an email field as the username field for my custom user model. I have the following custom User model subclassing Django\'s AbstractUser model:



        
4条回答
  •  抹茶落季
    2020-12-15 05:52

    Ian, thank you very much for the clever response :)

    However, I've already "patched" me a solution.

    Since AbstractUser also have a username field which is totaly unnecessary for me
    I decided to create my "own" AbstractUser.

    By subclassing AbstractBaseUser and PermissionsMixin I retain most of the User model built-in methods without adding any code.

    I also took advantage of that opportunity to create a custom Manager to eliminate the use in username field all together:

    from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
    
    class CustomUser(AbstractBaseUser, PermissionsMixin):
         ....
         email = models.EmailField(max_length=255, unique=True)
         first_name = ...
         last_name = ...
         is_active = ...
         is_staff = ...
         ....
    
         objects = CustomUserManager()
    
         USERNAME_FIELD = 'email'
    
    
    class CustomUserManager(BaseUserManager):
         def create_user(self, email, password=None, **extra_fields):
              .....
    
         def create_superuser(self, email, password, **extra_fields):
              .....
    

    This solution does result in repetition of some of Django's built-in code (mainly model fields that already exist in AbstractUser such as 'first_name', 'last_name' etc.) but also in a cleaner User object and database table.

    It is a real shame that the flexibily introduced in 1.5 with USERNAME_FIELD can not be used to actualy create a flexible User model under all existing constrains.

    EDIT: There is a comprehensive worked example available in the official docs: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#a-full-example

提交回复
热议问题