Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Please correct the error below" in the Django admin when using custom user models

Tags:

django

I am working on a Django app and I followed exactly these instructions to build a custom User.

Now when I try to create a new user from the admin panel, I get this error message enter image description here

so not very useful. Also I have the same problem whether I use the "change" form or the "create" form.

However if I try to create a new user through the shell, like

MyUser.objects.create_user(email="[email protected]", password=None)

it works.


Troubleshooting

Here is the model of the custom user:

class MyUser(AbstractBaseUser):
    """
    A base user on the platform. Users are uniquely identified by
    email addresses.
    """
    email = models.EmailField(
        verbose_name = "Email address",
        max_length   = 100,
        unique       = True
    )
    is_active  = models.BooleanField(default=True, blank=True)
    is_admin   = models.BooleanField(default=False, blank=True)

    @property
    def is_staff(self):
        return self.is_admin

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ()

    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.email

    def __unicode__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        '''Does the user have a specific permission?'''
        return True

    def has_module_perms(self, app_label):
        '''Does the user have permissions to view the app `app_label`?'''
        return True
  • One explanation is that it has something to do with a field of MyUser that has blank=False but that is not displayed by my ModelForm. I double checked, and it's fine.

  • Another explanation would be that the validation of the admin creation form has somehow inherited from the default User model of django.contrib.auth and it is trying to find a field from User that does not exist in MyUser. How can I check that?

  • Any idea?

like image 687
Buddyshot Avatar asked Sep 11 '14 23:09

Buddyshot


People also ask

How do I register a user model in Django admin?

from django. contrib import admin # Register your models here. Register the models by copying the following text into the bottom of the file. This code imports the models and then calls admin.

How can I remove extra's from Django admin panel?

You can add another class called Meta in your model to specify plural display name. For example, if the model's name is Category , the admin displays Categorys , but by adding the Meta class, we can change it to Categories . Save this answer.

What is Admin Py and what is the Django admin interface?

Django provides a default admin interface which can be used to perform create, read, update and delete operations on the model directly. It reads set of data that explain and gives information about data from the model, to provide an instant interface where the user can adjust contents of the application .


2 Answers

I had a similar problem. But it wasn't in the Admin form, it was at the admin list. I was using list_editable fields. When I would save changes, I would get the "Please correct the error below" message with nothing highlighted.

My error was that I had included the first field in the list_display as list_editable. To correct it, I add 'id' to the front of the list_display fields.

like image 129
RandO Avatar answered Oct 28 '22 18:10

RandO


Problem

I had a similar problem. But that's pretty easy to solve.


How to solve it step by step?

First of all we need to talk about overriding, as you said before. Django by default uses username field in models. And you need to change it like this in your models.py:

USERNAME_FIELD = 'email'

If you still really want to override a lot of code, next: create managers. Something about this: django managers In your custom manages class you need to override user creation (create_user method) and create_superuser method With this samples:

def create_user(self, email, password, **extra_fields):
    """
    Create and save a User with the given email and password.
    """
    log.debug(f'Creating user: {email}')
    if not email:
        raise ValueError(_('The email must be set'))
    email = self.normalize_email(email)
    user = self.model(email=email, **extra_fields)
    user.set_password(password)
    user.save()
    log.info('Created user %s', repr(user))

Only after all this steps you can take care about overriding existing forms. Django doc about this: https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#custom-users-admin-full-example implementation:

class CustomUserCreationForm(UserCreationForm):

    class Meta(UserCreationForm):
        model = CustomUser
        fields = ('email', )


class CustomUserChangeForm(UserChangeForm):

    class Meta:
        model = CustomUser
        fields = ('email', )

This forms are used for user Creation in your admin and User changing. And only now you can add code in your admin.py and change your UserAdmin like that:

@admin.register(CustomUser)
class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('first_name', 'last_name',)}),
        ('Permissions', {
            'fields': ('is_admin',),
        }),
        ('Important dates', {'fields': ('last_login',)}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'password1', 'password2', 'is_admin', 'is_root', )}
         ),
    )
    list_display = ('email', 'first_name', 'last_name', 'is_admin', 'created_at', 'updated_at',)
    list_filter = ('is_admin',)
    search_fields = ('email', 'first_name', 'last_name',)
    ordering = ('email',)
    filter_horizontal = ()

Be sure to add add_fieldsets and to override ordering by email. In add_fieldsets you need to 2 type of passwords. If there be only 1 - error occures. From your screen by the way.


I hope this helps everyone who ever encounters this problem.

like image 45
r1v3n Avatar answered Oct 28 '22 20:10

r1v3n