【问题标题】:Django: Updating models, new instance created instead of updatedDjango:更新模型,创建新实例而不是更新
【发布时间】:2015-05-01 11:25:24
【问题描述】:

我正在尝试为网站上的用户制作一个简单的个人资料编辑表单。我遵循了更新的标准建议,在文档中它说 Django 检测到实例主键并知道更新而不是插入。

唯一的问题是,当我尝试更新时,我得到了一个插入。我用模型实例(我试图编辑的实例)预先填充了一个表单,但是当我尝试保存它时,我得到了一个新实例。当我添加“force_update=True”行时,我收到一条错误消息,告诉我没有检测到主键。不知道为什么,因为我用模型实例预先填充了表单,但显然 pk 不是表单的一部分。我有什么遗漏吗?

一些代码:

型号:

class profile(models.Model):
    user = models.ForeignKey(User)
    first_name = models.CharField(max_length=20, null=True)
    last_name = models.CharField(max_length=20, null=True)
    DOB = models.DateField(null=True)
    age = models.IntegerField(null=True)
    public_email = models.EmailField(null=True)
    county = models.CharField(max_length=20, null=True)
    town = models.CharField(max_length=30, null=True)

形式:

class profileForm(forms.ModelForm):
    class Meta:
        model = profile
        exclude = ['user']

观点:

@login_required()
def edit_profile(request):
    if request.POST:
        proform = profileForm(request.POST)
        if proform.is_valid():
            prof = proform.save(False)
            prof.user = request.user
            prof.save(force_update=True)

        return HttpResponseRedirect('/accounts/view_profile/')
    else:
        c = {}
        if profile.objects.filter(user=request.user).exists():
            prof = profile.objects.get(user=request.user)
            c['proform'] = profileForm(instance=prof)
        else:
            c['proform'] = profileForm()

        return render(request, 'edit_profile.html', c)

非常感谢任何帮助!

【问题讨论】:

    标签: django-models model django-forms updatemodel


    【解决方案1】:

    我明白了,原来我只是想在表单上调用 save() 而不指定表单相关的特定实例。

    代码:

    @login_required()
    def edit_profile(request):
        c = {}
        if profile.objects.filter(user=request.user).exists():
            profModel = profile.objects.get(user=request.user)
            c['proform'] = profileForm(instance=profModel)
        else:
            c['proform'] = profileForm()
    
        if request.POST:
            # this line here, added 'instance=profModel' to specify
            # the actual instance i want to save
            proform = profileForm(request.POST, instance=profModel)
            if proform.is_valid():
                prof = proform.save(False)
                prof.user = request.user
                prof.save()
    
            return HttpResponseRedirect('/accounts/view_profile/')
        else:
    
            return render(request, 'edit_profile.html', c)
    

    有效!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-27
      • 1970-01-01
      • 2023-03-10
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 2012-02-22
      相关资源
      最近更新 更多