I write a custom user class - CustomUser
in models.py
, mainly followed here
import re
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.mail import send_mail
from django.core import validators
from django.contrib.auth.models import (AbstractUser, PermissionsMixin,
UserManager)
class CustomUser(AbstractUser, PermissionsMixin):
"""
custom user, reference below example
https://github.com/jonathanchu/django-custom-user-example/blob/master/customuser/accounts/models.py
"""
username = models.CharField(_('username'), max_length=30, unique=True,
help_text=_('Required. 30 characters or fewer. Letters, numbers and '
'@/./+/-/_ characters'),
validators=[validators.RegexValidator(
re.compile('^[\w.@+-]+$'), _('Enter a valid username.'), 'invalid')
])
email = models.EmailField(_('email address'), max_length=254)
create_time = models.DateTimeField(auto_now_add=True)
active = models.BooleanField() # if we can retrieval it from outside
objects = UserManager()
USERNAME_FIELD = 'username'
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def email_user(self, subject, message, from_email=None):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email])
def __str__(self):
return self.username
Then I registered it in admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import CustomUser
# Register your models here.
class CustomUserAdmin(UserAdmin):
model = CustomUser
admin.site.register(CustomUser, CustomUserAdmin)
But when I run python manage.py createsuperuser
to create a superuser, I got the following error:
ERRORS:
myapp.CustomUser.is_superuser: (models.E006) The field 'is_superuser' clash
es with the field 'is_superuser' from model 'myapp.customuser'.
The is_superuser
field is defined on PermissionMixin
. However, AbstractUser
also subclasses PermissionMixin
, so you're effectively inheriting from the same class twice. This causes the field clash, as older versions of Django don't allow subclasses to override fields (recent versions allow to override fields that are defined on abstract base classes).
You either have to inherit from AbstractBaseUser
and PermissionMixin
, or from just AbstractUser
. AbstractUser
defines some additional fields, including username
, is_staff
and is_active
, and some other things.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With