问题:类没有对象成员

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))

该函数的第一行在出现错误Question.objects.all()

E1101:类“问题”没有对象“成员”

我正在阅读Django文档教程,并且它们具有相同的代码并正在运行。

我尝试调用实例。

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

我的models.py类代码也是这个…

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

无济于事,我仍然有此错误。

我已经读过有关pylint的文章,并进行了…

pylint --load-plugins pylint_django

这没有帮助,即使github自述文件说…

防止有关Django生成的属性(例如Model.objects或Views.request)的警告。

我在我的virtualenv中运行了命令,但是什么也没有。

因此,任何帮助都会很棒。

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.


回答 0

pylint-django使用pip如下安装

pip install pylint-django

然后在Visual Studio Code中转到:用户设置Ctrl+ ,或文件>首选项>设置(如果可用))放入以下内容(请注意VSC中自定义用户设置所需的花括号):

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

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"
],}

回答 1

@ tieuminh2510的答案是完美的。但是在较新版本的VSC中,您将找不到在用户设置中编辑或粘贴该命令的选项。现在以较新的版本添加该代码,请按照以下步骤操作

ctr + sft + P打开“ 命令面板”。现在,在命令面板中键入首选项:配置特定语言的设置。现在选择Python。在右侧粘贴此代码

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

里面第一个大括号。确保pylint-django

希望这会有所帮助!

@tieuminh2510 answer is perfect. But in newer versions of VSC you will not find thhe option to edit or paste that command in User Settings. Now in newer version to add that code follow this steps :

Press ctr+sft+P to open the the Command Palette. Now in command palette type Preferences: Configure Language Specific Settings. Now select Python. Here in right side paste this code

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

Inside the first curly braces. Make sure that pylint-django.

Hope this will help!


回答 2

安装Django pylint:

pip install pylint-django

ctrl + shift + p>首选项:配置特定于语言的设置> Python

适用于python语言的settings.json应该如下所示:

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

    "[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]": {

    }
}

回答 3

这是答案。从我的reddit帖子中获得… https://www.reddit.com/r/django/comments/6nq0bq/class_question_has_no_objects_member/

这不是错误,只是来自VSC的警告。Django会动态地将该属性添加到所有模型类中(它在幕后使用了很多魔法),因此IDE不会通过查看类声明来了解该属性,因此会警告您可能存在的错误(不是)。对象实际上是一个帮助查询数据库的Manager实例。如果您真的想摆脱该警告,则可以转到所有模型并添加object = models.Manager()现在,VSC将看到声明的对象,并且不会再次抱怨。

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.


回答 4

我已经尝试了所有可能的解决方案,但不幸的是,我的vscode设置不会更改其linter路径。因此,我尝试在设置>用户设置> python中探索vscode设置。找到Linting:Pylint路径并将其更改为“ pylint_django”。别忘了在设置>用户设置> python配置中将linter更改为“ pylint_django”,从“ pyLint”更改为“ pylint_django”。

林特路径编辑

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


回答 5

VS CODE 1.40.0的更新

完成后:

$ pip install pylint-django

请点击以下链接:https : //code.visualstudio.com/docs/python/linting#_default-pylint-rules

请注意,要pylint考虑的方法pylint-django是通过指定:

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

settings.jsonVS Code中。

但是之后,您会发现很多新的掉毛错误。然后,阅读此处的内容:

只要将python.linting.pylintUseMinimalCheckers设置为true(默认值),就会传递这些参数。如果在中指定值pylintArgs或使用Pylint配置文件(请参阅下一节),则将pylintUseMinimalCheckers其隐式设置为false

我所做的就是.pylintrc按照链接中的描述创建一个文件,然后在文件中配置以下参数(不影响文件的其余部分):

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

现在pylint可以正常工作了。

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.


回答 6

您可以将linter for Python扩展更改为Visual Studio Code。

在VS中,打开命令面板Ctrl + Shift + P并键入以下命令之一:

Python:选择Linter

当您选择短绒时,它将被安装。我尝试了flake8,看来问题已解决。

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.


回答 7

只需添加@ Mallory-Erik所说的话:您可以将objects = models.Manager()其放在模式中:

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()

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()

回答 8

首先使用以下命令安装pylint-django

$ pip install pylint-django

然后运行第二条命令,如下所示:

$ pylint test_file.py --load-plugins pylint_django

–load-plugins pylint_django是正确检查django代码所必需的

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


回答 9

如果您使用python 3

python3 -m pip install pylint-django

如果python <3

python -m pip install pylint-django==0.11.1

注意:2.0版要求pylint> = 2.0,该版本不再支持Python 2!(https://pypi.org/project/pylint-django/

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/)


回答 10

通过执行操作Question = new Question()(我假设new是错字),您将用的实例覆盖Question模型Question。就像Sayse在评论中所说:不要为变量使用与模型名称相同的名称。因此,将其更改为类似my_question = Question()

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().


回答 11

如何抑制特定于每个错误的每一行上的错误?

像这样的东西:https : //pylint.readthedocs.io/en/latest/user_guide/message-control.html

错误:[pylint]类’class_name’没有’member_name’成员可以通过以下方法在该行上取消显示:

  # pylint: disable=no-member

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

回答 12

将您的linter更改为-flake8,问题将消失。

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


回答 13

当我使用pylint_runner时发生此问题

所以我要做的是打开.pylintrc文件并将其添加

# 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

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

回答 14

我能够更新用户settings.json

在我的Mac上,它存储在:

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

在其中设置以下内容:

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

那为我解决了这个问题。

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.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。