CholoBoy
CholoBoy

Reputation: 159

on_delete error for Django

I'm currently doing some projects from a book called Python Crash Course by Eric Matthes. Currently, I'm doing lab 19.1 where I have to use previous code to make a Django project while changing some of his own code but ran into a problem. Every time I want to run this command

>>>python manage.py makemigration blogs

in return, I get this code

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

His original models.py code:

from django.db import models

class Topic(models.Model):
    """A topic the user is learning about."""
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True) 

    def __str__(self):
        """Return a string representation of the model."""
        return self.text

class Entry(models.Model):
    """Something specific learned about a topic."""
    topic = models.ForeignKey(Topic)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'entries'

    def __str__(self):
        """Return a string representation of the model."""
        return self.text[:50] + "..."

and my current code:

from django.db import models

# Create your models here.

class BlogPost(models.Model):
    title = models.CharField(max_length=200)
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        """Return a string representation of the model."""
        return self.text

class Post(models.Model):
    """SThe post"""
    topic = models.ForeignKey(BlogPost)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'posts'

    def __str__(self):
        if len(self.text) >= 50:
            """Return a string represerntation of the model"""
            return self.text[:50] + "..."
        else:
            return self.text

I honestly do not know why I'm getting this error code I've check to see if I messed something up but I cannot find anything. Is there anyone that may know?

Upvotes: 1

Views: 1554

Answers (1)

scharette
scharette

Reputation: 10007

Since Django 2.x, on_delete is required. This is from the Django 2.0 relase notes:

The on_delete argument for ForeignKey and OneToOneField is now required in models and migrations. Consider squashing migrations so that you have fewer of them to update.

Therefore, the error comes from this line:

topic = models.ForeignKey(BlogPost)

You're creating a Foreign key relationship without providing the on_delete property. So, follow the link and pick the one that suits your needs.

Upvotes: 1

Related Questions