djangodjango-forms

Validation using DeleteView before deleting instance


What's the best approach for handling deletion of an object with some validation before the object is deleted? For example, in my setup have two models - Game and Team (which are obviously related). Users should only be able to delete teams that are NOT tied to any games.

I created a form (without any fields) for deleting a team...

class TeamDeleteForm(ModelForm):
    class Meta:
        model = Team
        fields = []

    def clean(self):
        # Check to see if this team is tied to any existing games
        if self.instance.gameteams_set.exists():
            raise ValidationError("This team is tied to 1 or more games")
        return super().clean()

But then I realized that the class based view DeleteView doesn't have any sort of form_valid() method. Should I extend the generic FormView instead of DeleteView or is there a better approach that I'm missing?


Solution

  • I think the best approach will be overriding the model's delete method. For example:

    class Team(models.Model):
        ...
        def delete(self, *args, **kwargs):
            if Game.objects.filter(team__pk= self.pk).exists():
                raise Exception('This team is related to a game.')  # or you can throw your custom exception here.
            super(Team, self).delete(*args, **kwargs)