Django UpdateView get_context_data函数调用两次

时间:2022-11-13 19:22:52

Here is the thing: I have two models - Group and Storage.And I want to update the data.But my model Group can update my data,and my model Storage can't.So I debug my code,and find the reason why my Storage data can't update: the funtion get_context_data() called twice.Once on the page load,Twice on the form post.But function form_valid isn't called. All same code,but different result.Someone can tell me why this happen? Thanks

这是事情:我有两个模型 - 组和存储。我想更新数据。但我的模型组可以更新我的数据,我的模型存储不能。所以我调试我的代码,找到原因我的存储数据无法更新:函数get_context_data()调用两次。一旦页面加载,表单上的两次post.But函数form_valid不被调用。所有相同的代码,但结果不同。有人可以告诉我为什么会这样?谢谢

Code:

class Group(models.Model):
  id=models.AutoField(primary_key=True)
  name=models.CharField(max_length=100,default='')
  info=models.CharField(max_length=100,default='')
class Storage(models.Model):
  id=models.AutoField(primary_key=True)
  disk_size=models.CharField(max_length=100,default="")
  disk_path=models.CharField(max_length=100,default="")
  info=models.CharField(max_length=100,default="")

class ManagerStorageUpdateView(LoginRequiredMixin,UpdateView):
  model = models.Storage
  form_class = forms.StorageCreateUpdateForm
  template_name = 'new_update_storage.html'
  success_url = reverse_lazy('manager:storage')

  def get_context_data(self, **kwargs):
    context = super(ManagerStorageUpdateView, self).get_context_data(**kwargs)
    hosts = models.Host.objects.all()
    storage_hosts = [host.id for host in self.object.hosts.all()]
    context.update({
        'hosts':hosts,
        'storage_hosts':storage_hosts
    })
    return context

  def form_valid(self, form):
    host_storage = form.save()
    hosts_id_list = self.request.POST.getlist('hosts',[])
    hosts = models.Host.objects.filter(id__in=hosts_id_list)
    host_storage.hosts.clear()
    host_storage.hosts.add(*hosts)
    host_storage.save()
    return super(ManagerStorageUpdateView,self).form_valid(form)

  def get_success_url(self):
    return self.success_url

1 个解决方案

#1


0  

The fact that form_valid() isn't called that means your form has some errors. You may want to display those on the page. And most likely this is the reason its calling get_context_data() for POST request as well.

事实上,form_valid()未被调用,这意味着您的表单有一些错误。您可能希望在页面上显示这些内容。而且很可能这也是它为POST请求调用get_context_data()的原因。

#1


0  

The fact that form_valid() isn't called that means your form has some errors. You may want to display those on the page. And most likely this is the reason its calling get_context_data() for POST request as well.

事实上,form_valid()未被调用,这意味着您的表单有一些错误。您可能希望在页面上显示这些内容。而且很可能这也是它为POST请求调用get_context_data()的原因。