Django /重复键值违反了唯一约束

时间:2017-10-02 22:04:00

标签: python django views django-users

我尝试使用OneToOneField扩展django auth用户模型,但无法解决此问题。

  

重复键值违反唯一约束“users_profile_user_id_key”   DETAIL:Key(user_id)=(67)已经存在。

我仔细研究了这个问题,有人说db不同步。

views.py

def create_profile(request):
if request.method == 'POST':
    user_form = UserRegistrationForm(request.POST)
    profile_form = UserProfileForm(request.POST)
    if user_form.is_valid() and profile_form.is_valid():
        registration = user_form.save()
        profile = profile_form.save(commit=False)
        profile.user = registration
        profile.save()
        return redirect('index')
else:
    user_form = UserRegistrationForm()
    profile_form = UserProfileForm()

return render(request, 'registration/registration.html', 
                                            {'user_form': user_form, 
                                            'profile_form': profile_form})

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    user_image = models.ImageField(upload_to="blog/assets",
                               default="blog/assets/people-photo.jpg",
                               null=True)
    birth_date = models.DateField(null=True, blank=True)


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

forms.py

class UserRegistrationForm(forms.ModelForm):

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'username', 'password')
        widgets = {
            'password': forms.PasswordInput(),
        }

class UserProfileForm(forms.ModelForm):

    class Meta:
        model = Profile
        fields = ('user_image', 'birth_date',)

1 个答案:

答案 0 :(得分:2)

您最麻烦的是:您尝试创建配置文件的双倍时间: 通过信号和形式。 也许你可以删除信号。

或尝试使用get_or_create代替简单create,因为我可以看到它不会破坏您的逻辑

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.get_or_create(user=instance)
        #              ^^^^^^^^^^^^^^

并覆盖保存表单:

if user_form.is_valid() and profile_form.is_valid():
    registration = user_form.save()
    # Set user password
    registration.set_password(user_form.cleaned_data.get('password'))
    profile_form = UserProfileForm(request.POST, instance=registration.profile)
    if profileis_valid():
        profile.save()