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.