Django - 用户配置文件:UNIQUE约束失败:main_userprofile.user_id

时间:2017-08-02 13:02:38

标签: django django-views

我正在尝试为现有的用户模型构建配置文件模型。

models.py

class UserProfile(models.Model):
    first_name = models.CharField(max_length=12,null=True)
    last_name = models.CharField(max_length=12,null=True)
    avatar = models.ImageField(null=True,upload_to='media_file/avatar/')
    user = models.OneToOneField(User,on_delete=models.CASCADE, 
    related_name='profile',unique=True)
    bio = models.TextField(max_length=500)
    birthday = models.DateTimeField(
        blank=True, null=True)

    def create_profile(sender, **kwargs):
        user = kwargs["instance"]
        if kwargs["created"]:
            user_profile = UserProfile(user=user)
            user_profile.save()
    post_save.connect(create_profile, sender=User)

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

所以我将forms.py构建为:

class UserProfileForm(forms.ModelForm):
 birthday = forms.DateField(widget=forms.SelectDateWidget)

 class Meta:
    model = UserProfile
    fields = "__all__"
    exclude =["user"]

我写了这样的views.py:

def profile_form_update(request):
    if request.method =="GET":
        form = UserProfileForm()
        return render(request,"profile_form.html",{"form":form})

    if request.method == 'POST':
        instance = get_object_or_404(UserProfile, user=request.user)
        form =UserProfileForm (request.POST or None, request.FILES or None,)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.save()
        context = {
           "form":form,
           "instance": instance,}
    return render(request, "profile_form.html", context)

首先这是有效的,当我在django管理面板中创建个人资料时。当我尝试加载现有表单时,表单呈现与存储在数据库中的内容。当任何更改形式出现错误时:

IntegrityError at /profile/update/
UNIQUE constraint failed: main_userprofile.user_id

我知道我的问题是存储在用户模型中的现有数据。我做了一些谷歌,有人说:

  

您告诉UserProfiles UserProfiles.u_id是唯一的,它不是(空白/空)。所以你得到了错误。您可能需要考虑将u_id更改为AutoField primary_key。然后使用models.ForeignKey(' UserBase')

连接它们

1 个答案:

答案 0 :(得分:2)

在视图中尝试这样,你需要将实例传递给表单以便更新它,

def profile_form_update(request):
    instance = get_object_or_404(UserProfile, user=request.user)
    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES, instance=instance)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.save()
    else:
        form = UserProfileForm(instance=instance)
    context = {
       "form":form,
       "instance": instance,}
    return render(request, "profile_form.html", context)