Django 1.5 custom User model error. “Manager isn't available; User has been swapped”

吃可爱长大的小学妹 提交于 2019-12-03 08:42:59

问题


I extend the django user model as described in the dev doc. I wan't to keep most of the original User model features so I extend the AbstractUser class. I've defined in settings.py:

AUTH_USER_MODEL = 'myapp.CustomUser'

My user class:

class CustomUser(AbstractUser):
  custom_field = models.ForeignKey('OtherModel')
  objects = UserManager()

Everything seems to work fine but when I try to make it managed by the admin site:

admin.site.register(CustomUser, UserAdmin)

I get this error on the admin CustomUser creation page (after validation of the password confirmation form):

AttributeError: Manager isn't available; User has been swapped for 'myapp.CustomUser'

The point is that I need this model managed by the admin site in order to have the same creation process as with the original User model (two step process with password validation).


回答1:


You need only change form for adding user(overwrite clean_username and change User on get_user_model()

Full working example(If you inherited from AbstractUser)

from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm


class MyUserChangeForm(UserChangeForm):

    class Meta:
        model = get_user_model()

class MyUserCreationForm(UserCreationForm):

    class Meta:
        model = get_user_model()

    def clean_username(self):
        username = self.cleaned_data["username"]
        try:
            get_user_model().objects.get(username=username)
        except get_user_model().DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])

class MyUserAdmin(UserAdmin):
    form = MyUserChangeForm
    add_form = MyUserCreationForm
    fieldsets = (
        (None, {'fields': [('username', 'password'),]}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                   'groups', 'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
        )

admin.site.register(MyUser, MyUserAdmin)



回答2:


I struggled with this error for hours. For me I needed to remove all references to

from django.contrib.auth.models import User

and then replace it with:

from myapp.models import MyUser as User

This is assuming your custom User model is in an app called myapp and you called the model MyUser.

I'm using as User so that I don't have to change where my existing code that makes reference to the the User object from django.contrib.auth.models.

Good luck!

Alan

@aviars




回答3:


You probably should look at full example in official documentation:

https://docs.djangoproject.com/en/dev/topics/auth/customizing/#a-full-example

There are some uncovered questions (permissions handling, for example), but, at least, it's working.




回答4:


From Django docs:

You should also define a custom manager for your User model.




回答5:


Subclass AbstractUser already handle objects = UserManager() for you (this code on github at line 327). You don't need to define it in your model again.

I'm not sure why it come with that error. But below config seem work for me with latest Dev version.

Model.py:

class CustomUser(AbstractUser):
  custom_field = models.ForeignKey('OtherModel')
  # remove : objects = UserManager()



回答6:


I've found a solution: I don't use UserAdmin to register the CustomUser in the admin site, I use a custom ModelAdmin.

class CustomUserAdmin(admin.ModelAdmin):

  add_form = CustomUserCreationAdminForm
  add_fieldsets = (
    (None, {
        'classes': ('wide',),
        'fields': ('username', 'password1', 'password2')}
    ),
  )
  def get_fieldsets(self, request, obj=None):
    if not obj:
        return self.add_fieldsets
    return super(CustomUserAdmin, self).get_fieldsets(request, obj)

  def get_form(self, request, obj=None, **kwargs):
    defaults = {}
    if obj is None:
        defaults.update({
            'form': self.add_form,
            'fields': admin.util.flatten_fieldsets(self.add_fieldsets),
        })
    defaults.update(kwargs)
    return super(CustomUserAdmin, self).get_form(request, obj, **defaults)

Because I want to have a creation form different from the update form, I override the get_form function of the Model Admin as done in the UserAdmin django code. I also have created a custom Creation form for my custom user: CustomUserCreationForm

I received a response in the django-users mailing list that may be better than mine: Unregister the original User class from the admin site and then register the CustomUser with UserAdmin:

admin.site.unregister(User)
admin.site.register(CustomUser, UserAdmin)

Not tested yet.

EDIT: this last solution doesn't work

Regards




回答7:


UserAdmin is already registered to manage User, at the end of contrib/auth/admin.py

admin.site.register(User, UserAdmin)

Given you want to register UserAdmin with CustomUser, I think you would first have to unregister the User/UserAdmin pair:

admin.site.unregister(User)

then register your new model. Given the lack of control in the order of module loading, you could create a class derived from UserAdmin and manage your user model with it. This would work everytime, if I'm thinking properly.



来源:https://stackoverflow.com/questions/13568172/django-1-5-custom-user-model-error-manager-isnt-available-user-has-been-swap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!