Reputation: 325
When I run the following command:
python manage.py makemigrations
I have this error:
File "/home/user/project/myvirt/forum/boards/models.py", line 9, in <module>
class Topic(models.Model):
File "/home/user/project/myvirt/forum/boards/models.py", line 12, in Topic
board = models.ForeignKey(Board, related_name='topics', on_delete='cascade')
File "/usr/local/lib/python3.7/dist-packages/django/db/models/fields/related.py", line 801, in __init__
raise TypeError('on_delete must be callable.')
TypeError: on_delete must be callable.
My models.py content is:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Board(models.Model):
name = models.CharField(max_length=30, unique=True)
description = models.CharField(max_length=100)
class Topic(models.Model):
subject = models.CharField(max_length=255)
last_updated = models.DateTimeField(auto_now_add=True)
board = models.ForeignKey(Board, related_name='topics', on_delete='cascade')
creator = models.ForeignKey(User, related_name='topics', on_delete='cascade')
class Post(models.Model):
message = models.TextField(max_length=4000)
topic = models.CharField(Topic, related_name='posts', on_delete='cascade')
created_by = models.CharField(User, related_name='posts', on_delete='cascade')
created_at = models.DateTimeField(auto_now_add=True)
updated_by = models.CharField(User, related_name='posts', on_delete='cascade')
updated_at = models.DateTimeField(null=True)
This is an exercise in sample forum and seems to be a problem with on_delete='cascade'
.
I am using Django version 3.
Upvotes: 0
Views: 727
Reputation: 46
The error message on_delete must be callable
indicates that it should be callable instead of string.
Following the Django official documentation ForeignKey, and here is a example:
from django.db import models
class Car(models.Model):
manufacturer = models.ForeignKey(
'Manufacturer',
on_delete=models.CASCADE,
)
Upvotes: 1
Reputation: 2225
The problem is that in your model fields you are assigning a string for on_delete
. (-> `on_delete='cascade')
What you need to do is to assign (as the error tells you) a callable, like CASCADE
.
Example:
from django.db import models
class MyModel(models.Model):
my_relation = models.ForeignKey(
MyOtherModel,
on_delete=models.CASCADE,
)
...
Furthermore: You are setting related_name=XYZ
on all your fields. This is incorrect, because a related_name can only be assigned to fields which handle relations, like ForeignKey
.
Also see docs.
Upvotes: 2