2016-02-29 128 views
0

在我的Django項目中,我創建了一個應用程序以獲得有關已註冊用戶的其他信息。所以,我的模式是這樣的:Django - 重複鍵值違反了唯一約束條件

class UserProfile(models.Model): 
    class Meta: 
     verbose_name_plural = u'User Profile' 

    user = models.OneToOneField(User) 
    birthday = models.DateField(blank=True, null=True) 
    avatar = models.ImageField(upload_to='media/profile/avatar', blank=True, null=True) 
    name = models.CharField(blank=True, null=True, max_length=20) 
    surname = models.CharField(blank=True, null=True, max_length=50) 
    phone = models.CharField(blank=True, null=True, max_length=12) 

    def __unicode__(self): 
     return '%s' % self.user 

這裏是我的登記表:

​​3210

這裏是查看我的登記表:

def UserProfileRegistration(request): 
    if request.user.is_authenticated(): 
     return HttpResponseRedirect('/profile/') 
    if request.method == 'POST': 
     form = RegistrationForm(request.POST) 
     if form.is_valid(): 
      user = User.objects.create_user(username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password']) 
      user.save() 
      user_profile = UserProfile(user=user) 
      user_profile.save() 
      return HttpResponseRedirect('/profile/') 
     else: 
      return render(request, 'profiles/registration.html', {'form':form}) 
     else: 
      form = RegistrationForm() 
      context = {'form':form} 
      return render (request, 'profiles/registration.html', context) 

在用戶配置文件我創建的ModelForm哪裏用戶可填寫UserProfile模型中的字段:

class ExtraProfileDataForm(ModelForm): 
    name = forms.CharField(label=(u'Enter your name')) 
    surname = forms.CharField(label=(u'Enter your surname')) 
    phone = forms.CharField(label=(u'Enter your phone')) 
    birthday = forms.DateField(label=(u'Enter birthday')) 
    avatar = forms.ImageField(label=(u'Enter avatar')) 

    class Meta: 
     model = UserProfile 
     fields = ('name', 'surname', 'phone', 'birthday', 'avatar') 

    def __init__(self, *args, **kwargs): 
     super(ExtraProfileDataForm, self).__init__(*args, **kwargs) 
     for key in self.fields: 
      self.fields[key].required = False 

這是模型形式的看法:

@login_required 
def UserFullDataForm(request): 
    if request.method == 'POST': 
     form = ExtraProfileDataForm(request.POST) 
     if form.is_valid(): 
      profile_user = request.user 
      user_profile = UserProfile(user=profile_user) 
      user_profile.name = form.cleaned_data['name'] 
      user_profile.surname = form.cleaned_data['surname'] 
      user_profile.phone = form.cleaned_data['phone'] 
      user_profile.birthday = form.cleaned_data['birthday'] 
      user_profile.avatar = form.cleaned_data['avatar'] 
      user_profile.save() 
      return HttpResponseRedirect('/profile/') 
      else: 
      return render(request, 'profiles/extra_profile.html', {'form':form}) 
     else: 
      form = ExtraProfileDataForm() 
      context = {'form':form} 
      return render (request, 'profiles/extra_profile.html', context) 

但是,當我填寫此表,我得到了錯誤: duplicate key value violates unique constraint "profiles_userprofile_user_id_key" DETAIL: Key (user_id)=(23) already exists. 在追蹤我看到這個錯誤在這行user_profile.save()。據我瞭解,發生這種情況是因爲此腳本使用相同的ID創建新項目,但未更新它。我必須更改我的代碼來更新現有項目,但不創建。謝謝。

回答

2

您需要使用get_or_create,如果發現它將返回一個現有項目;否則創建一個新的模型實例。

在用戶配置文件更新視圖:

user_profile, created = UserProfile.objects.get_or_create(user=profile.user) 

現在,而不是每次都創建一個新的配置文件 - 要更新,如果該用戶的配置文件已存在。

+0

非常感謝你的工作! –

相關問題