Gaz Zhao
Gaz Zhao

Reputation: 214

Python (Django): 'self.text' is unsubscriptable

I am learning Django following the book "Django for beginners", there is a strange problem. The code snippet below actually works, but Pylint keeps showing me an error, and I know the error happens. But the author did nothing about it. Does anyone know why, please? The code snippet is from my app folder's models.py.

from django.db import models

# Create your models here.
class Post(models.Model):
    text = models.TextField()

    def __str__(self):
        return self.text[:50]

The pylint error message in my vscode editor is - Value 'self.text' is unsubscriptable

My environment: Win 10, Python 3.6, Django 3.0.1

Upvotes: 3

Views: 712

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477616

The code snippet below actually works, but Pylint keeps showing me an error. Does anyone know why, please?

Yes, because Pylint does not "understand" the logic implemented in the metaclasses of a model and the fields. It thus thinks that self.text will return the TextField object, which is indeed not subscriptable. The metaclass will however "inject" a string for self.text.

There is a pylint-django package [pypi] that has a better understanding on how Django works, although it is still "limited". As one of the features it lists:

  • Fixes pylint’s knowledge of the types of Model and Form field attributes.

So normally it will fix this issue. Although it might still fail for custom model fields for example.

Upvotes: 3

Related Questions