Django:使用UpdateView中的post()使用实例的现有字段值填充表单的字段

时间:2016-09-18 06:29:48

标签: python django

我无法在UpdateView上获取当前实例的字段。如何根据其ID获取特定实例?

views.py

class ShowUpdate(UpdateView):
  model = Show
  fields = ['description', 'season', 'episode']

  def post(self, request, **kwargs):
      request.POST = request.POST.copy()
      request.POST['description'] = "how to get instance description?" # problem here
      request.POST['season'] = 2
      return super(ShowUpdate, self).post(request, **kwargs)

models.py

class Show(models.Model):
  owner = models.ForeignKey(User, null=True, default=True, related_name='o')
  title = models.CharField(max_length=100)
  description = models.TextField(default='N/A', blank=True, max_length=250)
  season = models.IntegerField(default=0)
  episode = models.IntegerField(default=0)

  def get_absolute_url(self):
      return reverse('show:index')

  def __str__(self):
      return self.title

1 个答案:

答案 0 :(得分:0)

查看UpdateView文档

此视图包含方法get_object(self, queryset=None)

在你的情况下,只需要在POST方法中调用它:

class ShowUpdate(UpdateView):
  model = Show
  fields = ['description', 'season', 'episode']

  def post(self, request, **kwargs):
      self.object = self.get_object()
      request.POST = request.POST.copy()
      request.POST['description'] = self.object.description
      request.POST['season'] = 2
      return super(ShowUpdate, self).post(request, **kwargs)