类没有'objects'成员。

6

我是新手学习Django,尝试创建一个小型市场。我创建了一个产品应用程序。这是视图文件views.py的代码:

from django.shortcuts import render
from django.http import HttpResponse
from products.models import product


def index(request):
  Products = product.objects.all()
  return render(request, 'index.html', {'products': Products})

def new(request):
  return HttpResponse('New Product')

这是针对models.py的内容:
from django.db import models


class product(models.Model):
  name = models.CharField(max_length=150)
  price = models.FloatField()
  stock = models.IntegerField()
  image_url = models.CharField(max_length=2083)

我也创建了一个模板文件夹,并将其用于实验:

<h1>Products</h1>
<ul>
  {% for product in Products %}
    <li>{{ product.name }}</li>
  {% endfor %}
</ul>

还有一些其他通常的代码。但是我在这部分收到了一个 Pylint 错误:

product.objects.all()

请帮助我!谢谢


1
既然您使用了return render(request, 'index.html', {'products': Products}),则在模板中应为{% for product in products %}。在Python中,通常使用class Product(models.Model):,然后使用products = Product.objects.all()。如果这样做,您的代码将对其他Python程序员更具可读性。 - Alasdair
4个回答

21

试试这个

使用pylint --generated-members=objects

安装Django pylint:

pip install pylint-django

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

Python语言的settings.json应该如下所示:

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

    "[python]": {

    }
}

2
这是因为PyLint不知道Django元类提供的objects属性。无论如何,您的E1101错误只是一个警告,您可以禁用它或使用特殊的pylint-django插件让PyLint意识到 Django 的魔法。
您代码的另一个问题是对传递给render调用的上下文的不正确使用:
return render(request, 'index.html', {'products': Products})

上下文是一个Python的 字典 对象,在模板中通过 key 可以访问到 value。您通过 key “products” 传递了查询集,但是在模板中遍历了 key “Products”(注意首字母大写),而该 key 并未设置,因此您的模板将无法渲染任何内容。

1

如果您在将其添加到settings.json文件后遇到错误,请尝试以下操作

enter code here
"python.linting.pylintArgs": [
    "--load-plugins=pylint_django",
    "--errors-only" 
],

0

还有另一个选项:~/.pylintrc 并编辑其中的一行,该行应为:

load-plugins=

并在其中添加Django插件:

load-plugins=pylint_django

当然,首先需要安装它:

python3 -m pip install pylint_django

没有pylint_django的egg包,但有pylint-django。因此应该使用pip install pylint-django进行安装。https://pypi.org/project/pylint-django/ - hipertracker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接