0

Hi I have a rare problem with my custom user for Django. This is my CustomUser code.

class CustomUser(AbstractBaseUser, PermissionsMixin):
    """ Custom User model. This class replace the default django user.
    """
    nick_validator =  [
        validators.RegexValidator(re.compile('^[\w.@+\- ]+$'), 
                                  'Introduce un nombre de usuario válido', 
                                  'invalid')
    ]

    help_texts = {
        'nick': '30 caracteres o menos. Caracteres válidos: letas, números'
                    ' y los caracteres @/./ /-/+/_',
        'avatar':(
            'Selecciona una imágen mayor que %(m)dx%(m)d y menor que '
            '%(M)dx%(M)d' % {'m': AVATAR_SIZE_MIN, 'M': AVATAR_SIZE_MAX}
        )
    }

    #Fields
    nick = models.CharField(max_length=30, unique=True,
                                validators=nick_validator,
                                help_text=help_texts['nick'])
    email = models.EmailField('Dirección e-mail', max_length=254, unique=True)
    is_active = models.BooleanField('Activo', default=True)
    is_staff = models.BooleanField('Está staff', default=False)
    date_joined = models.DateTimeField('Fecha de registro', auto_now_add=True)
    avatar = models.ImageField(upload_to=getAvatarPath, 
                               help_text=help_texts['avatar'],
                               default=settings.DEFAULT_AVATAR)

    objects = CustomUserManager()   #Object which make the users in shell.
    USERNAME_FIELD = 'nick'         #Field used as nick.
    REQUIRED_FIELDS = ['email']     #Required fields for the custom user.

    class Meta:
        verbose_name = 'Usuario'
        verbose_name_plural = 'Usuarios'


    def emailUser(self, subject, message, from_email=None):
        """ Send an email to the user.
            :param subject: Email subject
            :param message: Email message
            :param from_email: sender email
        """ 
        send_mail(subject, message, from_email, [self.email])

    def get_full_name(self):
        return '%s %s' % self.nick, self.email

    def get_short_name(self):
        return self.email

    def getUserUrl(self, action=None):
        #from django.utils.http import urlquote
        kwargs = {'nick': self.nick}
        if action!=None:
            kwargs['action'] = action

        return reverse('users:show_user', kwargs=kwargs)

    def getUserUrlComments(self):
        return self.getUserUrl('comentarios')

    def getUserUrlPosters(self):
        return self.getUserUrl('posters')

All correct, no?

When I make a new user using the admin panel show this message. enter image description here

You can see which appear an error, but it doesn't select any field indicating where is the error. Investigating a bit I changed the admin panel class and I added the field username (A field, which doesn't exists in my Custom User class)

class CustomUserAdmin(UserAdmin):
    list_display = ('nick', 'email', 'is_superuser')
    readonly_fields = ('date_joined',)
    fieldsets = (
        ('Información general', {'fields': ('username', 'nick', 'email', 'password',
                                 'date_joined', 'groups')}),
        ('Permisos', {'fields': ('is_active', 'is_staff', 'is_superuser', 
                                 'user_permissions')}),
        ('Información personal', {'fields': ('avatar', 'deleteAvatar')})
    )
    search_fields = ('nick', 'email')
    ordering = ('nick',)

    add_fieldsets = (
        ('Información general', {'fields': ('username', 'nick', 
                                            'email', 'password1',
                                            'password2')}),
        ('Permisos', {'fields': ('is_active', 'is_staff', 'is_superuser')}),
        ('Información personal', {'fields': ('avatar',)})
    )

    add_form = CustomUserCreationForm
    form = CustomUserChangeForm

I check again and this is the result. enter image description here

There is a hidden field (username) in my CustomUser. I didn't make this field in my customUser, neither appears in database table. Django add automatically this field. And I don't know how delete this field and use the "nick" field as USERNAME_FIELD. In custom forms this field no appears and i can create Users without problems. But in Panel admin i can't create any user.

I expect that you can solve my problem.

karthikr
  • 97,368
  • 26
  • 197
  • 188

1 Answers1

0

Username is required by default in django users which you are extending. You can check python inheritance.

Basically you have username, email and password fields by default plus the fields you add. Your Nick field is not necessary...that is done by the username already.

cdvv7788
  • 2,021
  • 1
  • 18
  • 26