﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
25148	Add a warning for `CASCADE`ing foreign keys on custom User models.	Flavio Curella	Flavio Curella	"Assume a custom user models is created as such:

{{{
class Taco(models.Model):
    flavor = models.CharField(max_length=64, unique=True)


class User(AbstractBaseUser):
    USERNAME_FIELD = 'username'

    username = models.CharField(max_length=64, unique=True)
    favorite_taco = models.ForeignKey(Taco, null=True)
}}}

When deleting the related object, the user will also be deleted because of cascading:

{{{
        taco = Taco.objects.create(flavor=""vegetarian"")
        user = User.objects.create_user(
            username='taco fan',
            favorite_taco=taco
        )
        User.objects.count()  # 1
        taco.delete()
        User.objects.count()  # 0
}}}

This is intended behavior, but it's still pretty dangerous and a common trap for beginners.

I'd like to leverage the system check framework to add a Warning whenever a FK with `on_delete=CASCADE` is added to a User model. Something along the lines of:

{{{
class AbstractUser():
    @classmethod
    def check(cls, **kwargs):
        errors = super(AbstractUser, cls).check(**kwargs)
        for field in cls._meta.fields:
            if isinstance(field, models.ForeignKey):
                if field.rel.on_delete == models.CASCADE:
                    errors.append(checks.Warning(
                        ""Field {0} is set to CASCADE on delete. You might lose users"".format(field.name),
                        hint=""Explicitly set {0}.on_delete to something else than `models.CASCADE"".format(field.name),
                        obj=field,
                        id=""{0}.W001"".format(cls._meta.app_label)
                    ))
        return errors
}}}

"	Uncategorized	closed	contrib.auth	1.8	Normal	duplicate			Unreviewed	0	0	0	0	0	0
