添加新用户时添加用户配置文件对象

时间:2012-02-28 04:02:12

标签: django-admin

您好我正在尝试添加用户个人资料对象,因为我添加了一个新用户但我总是得到“'用户'实例需要在使用多对多关系之前拥有主键值。”错误。

以下是我的用户个人资料类和管理员类:

class User_Profile(models.Model):
    user                = models.OneToOneField(User)
    country             = models.ForeignKey(Country)
    phone_number        = models.CharField(max_length=16)

    class Meta:
        db_table = 'user_profile'
        unique_together = ('user', 'country')

    def __unicode__(self):
        return self.user.username

class UserProfileInline(admin.StackedInline):
    model = User_Profile

class UserProfileAdmin(UserAdmin):
    add_form = AddUserForm
    fieldsets = (
        (None, {'fields': ('username',)}),
        (('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
        (('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}),
        (('Groups'), {'fields': ('groups',)}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'email', 'password1', 'password2')}
        ),
        (('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}),
        (('Groups'), {'fields': ('groups',)}),
    )
    inlines = [UserProfileInline]

    def save_model(self, request, obj, form, change):
        new_user = request.user
        new_user.save()
        user_profile = new_user.get_profile()
        user_profile.user = new_user
        user_profile.country = request.POST['country']
        user_profile.country = request.POST['phone_number']
        user_profile.save()

1 个答案:

答案 0 :(得分:0)

user = models.OneToOneField(User,primary_key = True)

也许你应该这样做。