3

So I'm working on the model.py in Django and i'm getting 2 pylint errors. I don't understand why? is this an issue with pylint or something i'm doing wrong in my code.

E1120:No value for argument 'on_delete' in constructor call    
E1136:Value 'self.text' is unsubscriptable
  • The first is on line 19, in Entry topic = models.ForeignKey(Topic)

  • The second is on line 24 self.text[:50]

If I remove the entry class the code works

from django.db import models

# Create your models here.
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] + "..."
mayhemds
  • 434
  • 1
  • 4
  • 13

3 Answers3

7

The problem was ForeignKey in Django 1.9 required 1 positional argument in Django 2.0 ForeignKey 2 required positional argument

  topic = models.ForeignKey("Topic", on_delete=models.PROTECT)
mayhemds
  • 434
  • 1
  • 4
  • 13
  • I'm facing the same issue. How did you resolve the "self.text is unsubscriptable" issue? This answer does not resolve that problem. – Jeff Moorhead Apr 02 '18 at 16:27
  • I removed the set number and left it blank. Not ideal but it worked. – mayhemds Apr 08 '18 at 14:59
  • 1
    I see you're learning from 'Python Crash Course'. Great choice. Used it myself. The reason `return self.text[:50] + "..."` isn't working is because Python doesn't recognize `self.text` as a String (because it's really a `models.TextField`) so it doesn't know how to interpret `[:50]` or how to concatenate it with `"..."`. When you get rid of the other stuff it knows to just cast it as a String, that's why that works. To get it to work as intended try `return str(self.text)[:50] + "..."`. That way `self.text` is now represented in its String form and you can perform String operations on it. – cbender Oct 30 '18 at 19:02
0

The reason of second issue is you missed the command after the command python manage.py makemigrations [appname], the missing command is python manage.py migrate.

Serenity
  • 35,289
  • 20
  • 120
  • 115
0

To prevent this, we should use on_delete=models.PROTECT.

By default Django uses on_delete=models.CASCADE but this is not secure if object deleted accidentally.

In that case there would be no notification of deleted objects so it would be ideal to use models.PROTECT.