0
您好我正在嘗試添加用戶配置文件對象,因爲我添加了一個新用戶,但我總是得到「'用戶'實例需要有一個主鍵值之前,很多關係都可以使用。「錯誤。當您添加新用戶時添加用戶配置文件對象
這裏是我的用戶配置文件類和管理類:
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()
哇。那就是訣竅。感謝 雖然我需要改變save_model有點 'DEF save_model(個體,請求,OBJ,形式,變更): new_user = OBJ new_user.save() 嘗試: user_profile = new_user.get_profile() user_profile.save() ,除User_Profile.DoesNotExist: user_profile = User_Profile(user = new_user,country = Country.objects.get(pk = request.POST ['user_profile-0-country']),phone_number = request.POST [ 'user_profile-0-phone_number']) user_profile.save(force_insert = True)' – fawx 2012-02-28 08:57:45