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

标签 python django view django-users

我尝试使用 OneToOneField 扩展 django 身份验证用户模型,但无法解决这个问题。

duplicate key value violates unique constraint "users_profile_user_id_key" DETAIL: Key (user_id)=(67) already exists.

我看了一下这个issue,有人说数据库不同步。

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',)

最佳答案

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

或者尝试使用 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()

关于python - Django/重复键值违反唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46534388/

相关文章:

sql - 如何查看物化 View 的原始脚本?

java - Raspberry Pi MAX31865 Python 到 Java 的转换

python - 考虑 NaN 值+Pandas 的采样数据帧

python - 使用 lambda 从头开始​​删除列表条目

python - 在服务器上运行 Django-selenium 项目

java - 动态添加 View 到LinearLayout

python - 如何在Python中设置魔术方法的默认行为?

python - Django-registration user_activated信号发送两次

python - 如何本地化 Google App Engine 上的应用程序?

swift - 如何在 Swift 中子类化自定义 UIViewController?