【问题标题】:class has no 'objects' member类没有“对象”成员
【发布时间】:2020-02-03 21:23:09
【问题描述】:

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

请帮助我!谢谢

【问题讨论】:

  • 既然你有return render(request, 'index.html', {'products': Products}),那么模板中应该是{% for product in products %}。在 Python 中,您通常使用class Product(models.Model):,然后是products = Product.objects.all()。如果你这样做,你的代码对于其他 Python 程序员来说将更具可读性。

标签: django python-3.x django-models


【解决方案1】:

试试这个 使用 pylint --generated-members=objects

安装 Django pylint:

pip install pylint-django

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

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

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

    "[python]": {

    }
}

【讨论】:

    【解决方案2】:

    这是因为PyLint 对提供objects 属性的Django 元类一无所知。无论如何,您的 E1101 error 只是一个警告,您可以禁用它或使用特殊的 pylint-django 插件来让 PyLint 了解 Django 所做的魔法。

    您的代码的另一个问题是传递给render 调用的上下文使用不正确:

    return render(request, 'index.html', {'products': Products})
    

    上下文是一个python dictionary 对象,其中value 可以通过key 在模板中访问。您正在通过 products 键传递您的查询集,但在您的模板中迭代 Products(注意第一个大写字母)键,该键未设置,因此您的模板不会呈现任何内容。

    【讨论】:

      【解决方案3】:

      添加到 settings.json 文件后出现错误的添加

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

      【讨论】:

        【解决方案4】:

        还有另一个选项:~/.pylintrc 并编辑以下行:

        load-plugins=
        

        并在其中添加 django 插件:

        load-plugins=pylint_django
        

        当然需要先安装哪个:

        python3 -m pip install pylint_django
        

        【讨论】:

          猜你喜欢
          • 2017-12-21
          • 1970-01-01
          • 2021-06-10
          • 1970-01-01
          • 1970-01-01
          • 2020-10-14
          • 2023-04-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多