Django: How to Fix “missing 1 required positional argument: on_delete”

A quick fix for missing 1 required positional argument: on_delete on Django 2.0

Django 2.0: a quick fix for "missing 1 required positional argument: on_delete"

Django 2.0 has been released with some nice improvements over the older version.

I really like the new path method so I decided to check out Django 2.0. Among the new feature there are some minor changes such as with the ForeignKey field.

Whether you’re upgrading Django or following an older tutorial you may stumble across the error:

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

Django raises the above error during the migration process:

python manage.py migrate

Up until Django 1.9 a model would like the following:

from django.db import models

class Article(models.Model):
    category = models.ForeignKey(Category)
    title =  models.CharField(max_length=55)
    # ...
    
    def __str__(self):
        return self.title

ForeignKey is a Django field for defining a many-to-one relationship.

Up until Django 1.9 the ForeignKey field required a single argument: the model to map to.

Since Django 2.0 the ForeignKey field requires two positional arguments:

  1. the model to map to
  2. the on_delete argument

You can find more about on_delete by reading the documentation.

For a quick fix of “missing 1 required positional argument: on_delete” update the model:

from django.db import models

class Article(models.Model):
    category = models.ForeignKey('Category', on_delete=models.PROTECT)
    title =  models.CharField(max_length=55)
    # ...
    
    def __str__(self):
        return self.title

After fixing ForeignKey you’ll be able to run migrations without any trouble:

python manage.py migrate

Be aware that on_delete is potentially destructive. Carefully read the documentation and choose wisely!

Check out Django 2.0 release notes for a list of the new features.

Thanks for reading!

More about Python on this blog: Come risolvere gli errori di scansione Google con Python

Valentino Gagliardi

Valentino Gagliardi

Consultant, Developer Coach. Are you stuck on a project? Let's talk!
Valentino Gagliardi

6 Replies to “Django: How to Fix “missing 1 required positional argument: on_delete””

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.