从django中基于类的通用视图中删除重复项

时间:2012-07-26 08:45:31

标签: python django django-views

class InvestigationCreateView(CreateView):
      form_class = InvestigationForm
      template_name = 'hse/investigation/investigation_create.html'
      success_url = reverse_lazy('hse-incidents')

      def get_context_data(self, **kwargs):
          context = super(InvestigationCreateView, self).get_context_data(**kwargs)
          id = self.kwargs['pk']
          incident = Incident.objects.get(id=id)
          context['incident'] = incident
          return context

      def form_valid(self, form):
          self.object = form.save(commit=False)
          id = self.kwargs['pk']
          incident = Incident.objects.get(id=id)
          self.object.incident = incident
          self.object.save()
          return HttpResponseRedirect(self.get_success_url())

在上面的代码中,语句 id = self.kwargs [' pk'] incident = Incident.objects.get(id = id)正在重复 get_context_data() form_valid()方法

我怎样才能避免在python中写这样的重复。

我尝试在同一个类中创建一个单独的方法,这个方法将在两个方法中调用,但这对我不起作用。

0 个答案:

没有答案