In Django 3, I want to delete an object and upon the user confirming the deletion, create an unrelated object. The code I wrote below creates the unrelated object as soon as the user clicks "delete", but before the user has confirmed the deletion. I want the unrelated object to be created upon confirmation of deletion.
class PromoteQuestionToMeta(DeleteView):
model = QuestionList
fields = []
template_name = 'search/questionlist_confirm_delete.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
questionlist_object = self.object
MetaQuestionList.objects.create(question=questionlist_object.question, created_by=questionlist_object.created_by)
return context
def get_success_url(self):
return reverse_lazy('home:home')
CodePudding user response:
You can override the .delete(…) method [Django-doc] and create an object:
class PromoteQuestionToMeta(DeleteView):
model = QuestionList
fields = []
template_name = 'search/questionlist_confirm_delete.html'
def delete(self, *args, **kwargs):
result = super().delete(*args, **kwargs)
MetaQuestionList.objects.create(
question=self.object.question,
created_by=self.object.created_by
)
return result
def get_success_url(self):
return reverse_lazy('home:home') 