Class has no objects member

PythonDjangoDjango Views

Python Problem Overview


def index(request):
   latest_question_list = Question.objects.all().order_by('-pub_date')[:5]
   template = loader.get_template('polls/index.html')
   context = {'latest_question_list':latest_question_list}
   return HttpResponse(template.render(context, request))

The first line of that function gets an error on Question.objects.all():

> E1101: Class 'Question' has no 'objects' member

I'm following the Django documentation tutorial and they have the same code up and running.

I have tried calling an instance.

Question = new Question()
and using MyModel.objects.all()

Also my models.py code for that class is this...

class Question(models.Model):
    question_text = models.CharField(max_length = 200)
    pub_date = models.DateTimeField('date published') 

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

    def __str__(self):
        return self.question_text

To no avail I still have this error.

I have read about pylint and ran this...

pylint --load-plugins pylint_django

Which didn't help, even tho the github readme file says...

> Prevents warnings about Django-generated attributes such as > Model.objects or Views.request.

I ran the command within my virtualenv, and yet nothing.

So any help would be great.

Python Solutions


Solution 1 - Python

Install pylint-django using pip as follows

pip install pylint-django

Then in Visual Studio Code goto: User Settings (Ctrl + , or File > Preferences > Settings if available ) Put in the following (please note the curly braces which are required for custom user settings in VSC):

{"python.linting.pylintArgs": [
     "--load-plugins=pylint_django"
],}

Solution 2 - Python

@tieuminh2510's answer is perfect. But in newer versions of VSC you will not find the option to edit or paste that command in User Settings.

For newer versions, add the code in the following steps:

  1. Press ctrl shift p to open the the Command Palette.
  2. Now in Command Palette type Preferences: Configure Language Specific Settings.
  3. Select Python.
  4. Add these lines inside the first curly braces:
    "python.linting.pylintArgs": [
            "--load-plugins=pylint_django",
        ]

> Make sure that pylint-django is also installed.

Solution 3 - Python

Install Django pylint:

pip install pylint-django

ctrl+shift+p > Preferences: Configure Language Specific Settings > Python

The settings.json available for python language should look like the below:

{
    "python.linting.pylintArgs": [
        "--load-plugins=pylint_django"
    ],
    
    "[python]": {

    }
}

Solution 4 - Python

I've tried all possible solutions offered but unluckly my vscode settings won't changed its linter path. So, I tride to explore vscode settings in settings > User Settings > python. Find Linting: Pylint Path and change it to "pylint_django". Don't forget to change the linter to "pylint_django" at settings > User Settings > python configuration from "pyLint" to "pylint_django".

Linter Path Edit

Solution 5 - Python

Heres the answer. Gotten from my reddit post... https://www.reddit.com/r/django/comments/6nq0bq/class_question_has_no_objects_member/

> That's not an error, it's just a warning from VSC. Django adds that > property dynamically to all model classes (it uses a lot of magic > under the hood), so the IDE doesn't know about it by looking at the > class declaration, so it warns you about a possible error (it's not). > objects is in fact a Manager instance that helps with querying the DB. > If you really want to get rid of that warning you could go to all your > models and add objects = models.Manager() Now, VSC will see the > objects declared and will not complain about it again.

Solution 6 - Python

UPDATE FOR VS CODE 1.40.0

After doing:

$ pip install pylint-django

Follow this link: https://code.visualstudio.com/docs/python/linting#_default-pylint-rules

Notice that the way to make pylint have into account pylint-django is by specifying:

"python.linting.pylintArgs": ["--load-plugins", "pylint_django"]

in the settings.json of VS Code.

But after that, you will notice a lot of new linting errors. Then, read what it said here:

>These arguments are passed whenever the python.linting.pylintUseMinimalCheckers is set to true (the default). If you specify a value in pylintArgs or use a Pylint configuration file (see the next section), then pylintUseMinimalCheckers is implicitly set to false.

What I have done is creating a .pylintrc file as described in the link, and then, configured the following parameters inside the file (leaving the rest of the file untouched):

load-plugins=pylint_django

disable=all

enable=F,E,unreachable,duplicate-key,unnecessary-semicolon,global-variable-not-assigned,unused-variable,binary-op-exception,bad-format-string,anomalous-backslash-in-string,bad-open-mode

Now pylint works as expected.

Solution 7 - Python

You can change the linter for Python extension for Visual Studio Code.

In VS open the Command Palette Ctrl+Shift+P and type in one of the following commands:

>Python: Select Linter

when you select a linter it will be installed. I tried flake8 and it seems issue resolved for me.

Solution 8 - Python

Just adding on to what @Mallory-Erik said: You can place objects = models.Manager() it in the modals:

class Question(models.Model):
    # ...
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    # ...
    def __str__(self):
        return self.question_text
    question_text = models.CharField(max_length = 200)
    pub_date = models.DateTimeField('date published')
    objects = models.Manager()

Solution 9 - Python

Change your linter to - flake8 and problem will go away.

Solution 10 - Python

I was able to update the user settings.json

On my mac it was stored in:

~/Library/Application Support/Code/User/settings.json

Within it, I set the following:

{
    "python.linting.pycodestyleEnabled": true,
    "python.linting.pylintEnabled": true,
    "python.linting.pylintPath": "pylint",
    "python.linting.pylintArgs": ["--load-plugins", "pylint_django"]
}

That solved the issue for me.

Solution 11 - Python

First install pylint-django using following command

$ pip install pylint-django

Then run the second command as follows:

$ pylint test_file.py --load-plugins pylint_django

--load-plugins pylint_django is necessary for correctly review a code of django

Solution 12 - Python

If you use python 3

python3 -m pip install pylint-django

If python < 3

python -m pip install pylint-django==0.11.1

NOTE: Version 2.0, requires pylint >= 2.0 which doesn’t support Python 2 anymore! (https://pypi.org/project/pylint-django/)

Solution 13 - Python

First, Install pylint-django using pip as follows:

pip install pylint-django

Goto settings.json find and make sure python linting enabled is true like this:

enter image description here

At the bottom write "python.linting.pylintPath": "pylint_django"like this:

enter image description here

OR,

Go to Settings and search for python linting

make sure Python > Linting: Pylint Enabled is checked

Under that Python > Linting: Pylint Path write pylint_django

Solution 14 - Python

How about suppressing errors on each line specific to each error?

Something like this: https://pylint.readthedocs.io/en/latest/user_guide/message-control.html

Error: [pylint] Class 'class_name' has no 'member_name' member It can be suppressed on that line by:

  # pylint: disable=no-member

Solution 15 - Python

I installed PyLint but I was having the error Missing module docstringpylint(missing-module-docstring). So I found this answer with this config for pylint :

"python.linting.pylintEnabled": true,
"python.linting.pylintArgs": [
    "--disable=C0111", // missing docstring
    "--load-plugins=pylint_django,pylint_celery",
 ],

And now it works

Solution 16 - Python

By doing Question = new Question() (I assume the new is a typo) you are overwriting the Question model with an intance of Question. Like Sayse said in the comments: don't use the same name for your variable as the name of the model. So change it to something like my_question = Question().

Solution 17 - Python

This issue happend when I use pylint_runner

So what I do is open .pylintrc file and add this

# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=objects

Solution 18 - Python

Just add objects = None in your Questions table. That solved the error for me.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbuuencryptedView Question on Stackoverflow
Solution 1 - Pythontieuminh2510View Answer on Stackoverflow
Solution 2 - PythonFightWithCodeView Answer on Stackoverflow
Solution 3 - Pythonuser3785966View Answer on Stackoverflow
Solution 4 - PythonWilly satrio nugrohoView Answer on Stackoverflow
Solution 5 - PythonbuuencryptedView Answer on Stackoverflow
Solution 6 - PythonamedinaView Answer on Stackoverflow
Solution 7 - PythonmothView Answer on Stackoverflow
Solution 8 - PythonLeRoyView Answer on Stackoverflow
Solution 9 - PythonVenu Gopal TewariView Answer on Stackoverflow
Solution 10 - PythonKingsley IjomahView Answer on Stackoverflow
Solution 11 - PythonChirag KalalView Answer on Stackoverflow
Solution 12 - PythonAshen OneView Answer on Stackoverflow
Solution 13 - PythonMahbub Ul IslamView Answer on Stackoverflow
Solution 14 - PythonPritam ManeraoView Answer on Stackoverflow
Solution 15 - PythonLucasView Answer on Stackoverflow
Solution 16 - Pythonvoodoo-burgerView Answer on Stackoverflow
Solution 17 - PythonTony NgoView Answer on Stackoverflow
Solution 18 - PythonPratham DaveView Answer on Stackoverflow