0
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())

In above code the statement id = self.kwargs['pk'] and incident = Incident.objects.get(id=id) are repeating in both the get_context_data() and form_valid() methods

How can i avoid writing such repeatation in python.

I tried by creating a separate method in the same class and which will be called in both the methods but that doesn't work with me.

Asif
  • 1,775
  • 4
  • 25
  • 39
  • 3
    I don't see no duplicate lines. –  Jul 26 '12 at 08:47
  • 1
    It will cost you more lines if you're going to class inherit and hack naming on init, which makes no sense. You could just use ListView.as_view() in your urls and add your variables as arguments to reduce code – Hedde van der Heide Jul 26 '12 at 09:11
  • Excuse me, I have given the incorrect answer. Decorators for classes can't get arguments in brackets. You can use metaclasses to create classes instead of the decorators in your case. Please see the next: http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python – sergzach Jul 26 '12 at 09:46

0 Answers0