【问题标题】:Override form.save() to not create new record but update existing record in db table each time it is executed覆盖 form.save() 以不创建新记录,而是在每次执行时更新 db 表中的现有记录
【发布时间】:2015-10-07 08:39:15
【问题描述】:

当我在视图中保存表单时,我正在努力防止在数据库表中创建新行。

我的视图中有以下代码

def checker(request):
  response_data=''
  if request.method == "POST":
    user_form1 = DocumentForm(request.POST, request.FILES) 
    if user_form1.is_valid(): 
        new_form = user_form1.save(commit=False)
        new_form.save()  # Image file gets uploaded in the server and new row gets created each time this gets executed
        user_form1.save_m2m()
        res=td_tab.objects.filter(id=request.session.get('proid')).update(profpicpath=new_form.profpicpath.url)
        response_data = 'Updated response'
else:
    form = DocumentForm() 
    response_data = 'Nothing to update!'
return HttpResponse(response_data, content_type="text/plain")

表格:

class DocumentForm(forms.ModelForm):
    profpicpath = forms.FileField()
    class Meta:
        model = td_tab
        fields = ('profpicpath',)

model 除了 profpicpath 之外还有几个字段。

问题是,在我看来,当 new_form.save() 被执行时,它正在数据库表中创建新记录:(

我希望为特定的 proid 更新现有记录.. 令人惊讶的是,下面的行在视图中不起作用..即使我使它起作用,也会创建新行,并且只有 profpicpath 字段会使用最新条目填充到数据库表中:(

res=td_tab.objects.filter(id=request.session.get('proid')).update(profpicpath=new_form.profpicpath.url)

如何防止在为检查器视图发出的每个请求中在 td_tab 表中创建新记录?

或者可能有一些技巧可以覆盖表单的 save() 方法,这样它只会更新现有记录,而不是为其每次执行创建新记录?

【问题讨论】:

    标签: django django-views


    【解决方案1】:

    您应该将模型实例传递给表单对象进行更新:

    your_instance = Model.objects.get(some_data=some_data)
    form = DocumentForm(request.POST or None, instance=your_instance)
    
    if form.is_valid():
       ...
       ...
       form.save()
    

    【讨论】:

      猜你喜欢
      • 2011-12-10
      • 2023-01-12
      • 2012-07-25
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      • 2010-11-23
      相关资源
      最近更新 更多