TypeError: __init__() got an unexpected keyword argument 'on_delete'

Viewed 11331

I built a model:

class Channel(models.Model):
    title = models.CharField(max_length=255, unique=True)
    slug = models.SlugField(allow_unicode=True, unique=True)
    description = models.TextField(blank=True, default='')
    description_html = models.TextField(editable=False, default='', 
blank=True)
    subscribers = models.ManyToManyField(User, 
through="ChannelMembers", on_delete=models.CASCADE,)

When I do makemigration it say :

TypeError: __init__() got an unexpected keyword argument 'on_delete'

And when a delete the on_delete it say:

TypeError: __init__() missing 1 required positional argument: 'on_delete'

What's worng?

1 Answers

on_delete is not a valid argument on a ManyToManyField. You would need to use the on_delete argument in each of the ForeignKey fields in the through model for ChannelMembers instead.

You can see the following example how this is achievable on the Django Docs website

In your case it would look something like this:

class Channel(models.Model):
    ...
    # Don't have the on_delete parameter on this field
    subscribers = models.ManyToManyField(User, through="ChannelMembers")

# Add on_delete to both the fields in this class instead
class ChannelMembers(models.Model):
    channel = models.ForeignKey(Channel, on_delete=models.CASCADE)
    subscriber = models.ForeignKey(User, on_delete=models.CASCADE)
Related