Peter Kam
Peter Kam

Reputation: 103

TypeError: on_delete must be callable

File "C:\Users\sungk\Git\django_website\blog\models.py", line 5, in <module>     class Post(models.Model):
File "C:\Users\sungk\Git\django_website\blog\models.py", line 10, in Post     author = models.ForeignKey(User, on_delete=True)   File "C:\Users\sungk\Git\django_website\venv\lib\site-packages\django\db\models\fields\related.py", line 813, in __init__     raise TypeError('on_delete must be callable.') TypeError: on_delete must be callable.

Upvotes: 2

Views: 924

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

The on_delete=… parameter [Django-doc] can not be True. It should be a callable, a function. Usually it is one of the builtins as described in the documentation. This can be CASCADE, PROTECT, RESTRICT, SET_NULL, SET_DEFAULT, SET(…), or DO_NOTHING.

Strictly speaking you can also make your own callable, but that is only applicable if you want to do something more sophisticated than the ones listed above.

The on_delete=… specifies what to do with the related Posts in case the User object that is the author is removed. By using CASDCADE, the related Post objects will be removed:

from django.conf import settings
from django.db import models

class Post(models.Model):
    author = models.FOreignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Upvotes: 2

Related Questions