【问题标题】:Name 'Customer' is not defined CBV ListView名称“客户”未定义 CBV ListView
【发布时间】:2018-10-24 08:04:37
【问题描述】:

urls.py

from django.conf.urls import url
from system import views

app_name = 'project'

urlpatterns = [
    ...
    url(r'^cust/([\w-]+)/$',views.PublisherBookList.as_view()),
    ...
]

views.py

from . import models

class PublisherBookList(ListView):

    def get_queryset(self):
        self.name = get_object_or_404(Customer, name=self.args[0])
        return Customer.objects.filter(name=self.name)

models.py

class Customer(models.Model):
    name = models.CharField(max_length=255)

我确实访问过http://127.0.0.1:8000/project/custo/customername/

收到错误name 'Customer' is not defined

我错过了什么?...

【问题讨论】:

  • 你导入客户模型了吗?
  • 是的,from . import models

标签: python django


【解决方案1】:

你需要在你的views.py中导入Customer

from .models import Customer 

【讨论】:

  • 已经做了,我有很多模型。只是在带有def get_queryset(self): 部分的视图上出错。
  • 您导入了模块,但没有导入类。您可以将导入更改为 from .models import Customer 或在任何地方使用 models.Customer 而不仅仅是 Customer
  • 啊,明白了。现在忘了做models. 它的工作,但没有任何结果。我检查了我的数据库名称John,将 John 放在 url 上,它什么也不显示。
  • 默认情况下,Django 详细视图使用pk url kwarg,这是对象的Django 数据库ID。如果你想使用自定义 slug attr,你需要添加一些东西。以下是相关问题:stackoverflow.com/questions/46815655/…
  • 这里解释了如何改变默认的slug字段stackoverflow.com/questions/5780803/…
猜你喜欢
  • 2014-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多