Search code examples
djangodjango-generic-views

Adding condition to DeleteView in Django


I am learning basics of Django and trying to add a condition before deletion of Ingredient instance in a generic DeleteView.

But it looks like DeleteView is just ignoring my condition. What am I doing wrong?

Thank you in advance for looking at my question!

class IngredientDelete(LoginRequiredMixin, DeleteView):
  model = Ingredient
  template_name = "inventory/ingredient_delete_form.html"
  success_url = "/ingredient/list"

  def delete(self, request, *args, **kwargs):
    object = self.get_object()
    if len(object.reciperequirement_set.all()) > 0:
      object.delete(save=False)
      messages.error("You can't delete an ingredient if it is used in Menu Items. Please update Menu items first. You can check related Menu items list on the Ingredient Details page")
      return render(request, "ingredient/<pk>", messages)
    else:
      return super().delete(request, *args, **kwargs)

in python shell, for the instance object I try len(object.reciperequirement_set.all()) and get 1, so I suppose the query in my condition is set correctly.

At local host page for the same Ingredient instance I get the error page:

ProtectedError at /ingredient/23/delete

("Cannot delete some instances of model 'Ingredient' because they are referenced through protected foreign keys: 'RecipeRequirement.ingredient'.", {<RecipeRequirement: menu item: testdel, price: 34.00, ingredient: testingr: 22.00 tsp>})

Request Method: POST Request URL: http://127.0.0.1:8000/ingredient/23/delete Django Version: 4.0.4 Exception Type: ProtectedError


Solution

  • Override test_func() with your own conditions.