开发者

Using new Admin Form when Customizing Django User Model

I am extending the User Model, but seem to be having a problem with using my new admin form. I have the following code in models.py:

    class Preference(models.Model):
        choice = models.TextField(choices = (('grid', 'grid'), ('list','list'))) 

        def __unicode__(self):
            return self.choice

    class UserProfile2(models.Model):
        preference 开发者_如何学编程= models.ForeignKey(Preference, default = Preference.objects.get(id=2).id)
        user = models.OneToOneField(User, unique=True)

    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            print 'creating user profile2'
            u = UserProfile2.objects.create(user=instance)   

    post_save.connect(create_user_profile, sender=User)

The following code is in admin.py:

    class UserProfileInline(admin.TabularInline):
        model = UserProfile2
        fk_name = 'user'

    class CustomUserAdmin(UserAdmin):
        inlines = [UserProfileInline,]

    admin.site.unregister(User)
    admin.site.register(User, CustomUserAdmin)     

The following is in settings.py:

    AUTH_PROFILE_MODULE = 'userextension.UserProfile2' 

It works correctly when the user does not try to control the value for preference object in the admin, and creates a new user using the default value. But if the user tries to switch away from the default value of 'list' and uses 'grid' instead, I get a 'Duplicate Entry for Key user_id' error.

Do I need to explicitly get the value from the admin form for the extra field and save both the userprofile2 object and the user object? If so, how is that related to the error I receive? I haven't found much documentation for how to do that, and would much appreciate any direction.

Update: This seems important, too: When I remove the default value for preference in the UserProfile2 model, the error I get is "Column 'preference_id' cannot be null"

Thanks for taking a look at my question.


Your signal creates a new UserProfile2 object on post_save of a User object, based on the value of 'created'. I'm betting that 'created' is True every time this signal is called, and it's trying to create a new UserProfile2 object each time you save any information on a User object in admin.

UserProfile2's user foreign key is set to unique, which is where you're getting the duplicate key error.

Try changing your signal code to:

def create_user_profile(sender, instance, created, **kwargs):
        if created:
            u = UserProfile2.objects.get_or_create(user=instance)

that should prevent the duplicate key error. Hope that helps you out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜