【问题标题】:'function' object has no attribute 'objects' error in django'function'对象在django中没有属性'objects'错误
【发布时间】:2015-04-02 09:56:29
【问题描述】:

关于这个错误有很多解决方案,但我仍然没有解决我的问题。我只想从表(产品)中打印一个列值(产品标题)。

Models.py 文件-

from django.db import models
class product(models.Model):
    product_title = models.CharField(max_length=50)
    product_image = models.ImageField(upload_to="images")
    product_desc = models.CharField(max_length=200)
    product_duration = models.CharField(max_length=50)

views.py 文件-

from django.shortcuts import render
from mutech.models import product
from django.shortcuts import render_to_response
from django.http import HttpResponse

def product(request):   
    return render_to_response('mutech/product.html',
                             {'product_row':product.objects.get(id="1") })

在 product.html 文件中,我使用它作为-

<h3>{{ product_row.product_title }}</h3>

并得到错误-

'function' object has no attribute 'objects' error in django.

【问题讨论】:

  • 函数和对象的名称好像相同?是在原始代码中吗?

标签: django database django-models


【解决方案1】:

在视图的 render_to_response 字典中,您指的是 project,您的视图,而不是 Product,您的模型。

【讨论】:

  • 但你仍然指的是product你的视图而不是Product你的模型。也许你应该给视图一个完全不同的名字,这样你就不会感到困惑了。
  • 感谢@Daniel Roseman,我已经更改了它,但我仍然给出同样的错误。
  • 不,我的第一条评论是在您编辑之后。 仍然指的是product视图而不是Product模型。.
  • 你说的是大写P吗,如果不是,请解释问题。
  • 是的,第三次了。 productProduct 不同。
【解决方案2】:

您收到此错误是因为您在 view.pymodel.py 中使用相同的命名约定。根据您的方便,使用product_info 或其他名称更改views.py 中的函数名称。

【讨论】:

    猜你喜欢
    • 2021-10-22
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 2020-11-13
    • 2017-07-07
    • 2021-01-12
    相关资源
    最近更新 更多