Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting TypeError: __init__() missing 1 required positional a rgument: 'on_delete'

'HOw to reslove this erroe I am using Django 3.0'

from django.db import models
# Create your models here.
class Topic(models.Model):
    top_name=models.CharField(max_length=264,unique=True)
    def __str__(self):
        return self.top_name
class Webpage(models.Model):
    topic= models.ForeignKey(Topic)
    name = models.CharField(max_length=264,unique=True)
    url = models.URLField(unique= True)

    def __str__(self):
        return self.name
class AccessRecord(models.Model):
        name = models.ForeignKey(Webpage)
        date = models.DateField()

        def __str__(self):
            return str(self.date)

I copied code of Django 1 version and I am using Django 3.0 version.

File "C:\Users\himan5hu\Documents\HTML\My_Django\first_project\first_app\models.py", line 7, in class Webpage(models.Model):

File "C:\Users\himan5hu\Documents\HTML\My_Django\first_project\first_app\models.py", line 8, in Webpage topic= models.ForeignKey(Topic)

topic= models.ForeignKey(Topic)
like image 812
Himanshu Rawat Avatar asked Jun 12 '26 10:06

Himanshu Rawat


1 Answers

Since django-2.0, it is mandator to specify an on_delete=… parameter [Django-doc] for a ForeignKey. Before django-2.0, it was by default CASCADE.

on_delete=… is a parameter that specifies what to do in case the target object is deleted. In case of CASCADE the Webpage will thus be removed if it points to a Topic that is removed.

You thus can fix this with:

from django.db import models

class Topic(models.Model):
    top_name=models.CharField(max_length=264,unique=True)
    def __str__(self):
        return self.top_name


class Webpage(models.Model):
    topic= models.ForeignKey(Topic, on_delete=models.CASCADE)
    name = models.CharField(max_length=264, unique=True)
    url = models.URLField(unique=True)

    def __str__(self):
        return self.name


class AccessRecord(models.Model):
        name = models.ForeignKey(Webpage, on_delete=models.CASCADE)
        date = models.DateField()

        def __str__(self):
            return str(self.date)

You will need to alter this in existing migration files as well.

It might however be useful to inspec the documentation, and look if another option might be more approriate.

like image 162
Willem Van Onsem Avatar answered Jun 13 '26 23:06

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!