I get 'NoneType' object has no attribute 'save' when I create a user with Django amdin.

I created a user using the AbstractUser class, and created a custom admin class to help me create users from the admin page, but when I create a user, I get ‘NoneType’ object has no attribute ‘save’ error. i can’t seem to resolve the problem.

My user

class Users(AbstractUser):
    email = models.CharField(max_length=100, blank=True)
    bio = models.CharField(blank=True, max_length=100)
    dp = models.URLField(blank=True)

My admin class



class UserCreationForm(forms.ModelForm):

    password1 = forms.CharField(label="Password", widget=forms.PasswordInput)
    password2 = forms.CharField(label="Password Confirmation", widget=forms.PasswordInput)
    bio = forms.CharField(widget=forms.Textarea, required=False)

    class Meta:
        model = Users
        fields = "__all__"

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            return user.save()

class UserChangeForm(forms.ModelForm):
    # reads only hashed password
    password = ReadOnlyPasswordHashField

    class Meta:
        model = Users
        #fields = "__all__"
        fields = ('email', 'password', 'bio', 'is_active', 'is_staff')

class UserAdmin(BaseUserAdmin):
    form = UserChangeForm
    add_form = UserCreationForm


    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ("username", 'email', 'first_name', 'last_name', 'password1', 'password2', "bio", "is_staff", "is_superuser", "dp", "groups")}
        ),
    )


admin.site.register(Users, UserAdmin)
admin.site.register(Permission)

Thank you.

The form .save() method expects that the saved instance is returned. But on your save method, you are returning user.save:

The .save() method on an Model instance always returns None, returning that will return None as well.

And also, you have an implicit return None here:

When commit is False then the function will exit, and return None.

Thank you very much, the doc I followed actually returned the user outside the if statement. It must have been an oversight.

1 Like