【问题标题】:AttributeError: Generic detail view must be called with either an object pk or a slugAttributeError:必须使用对象 pk 或 slug 调用通用详细视图
【发布时间】:2016-02-22 04:53:57
【问题描述】:

无法访问我的模型中的数据,出现下一个错误:AttributeError: Generic detail view Myview must be called with an object pk or a slug.

我的模特:

class product(models.Model):
    title = models.CharField(max_length = 1000)
    description = models.TextField(max_length = 5000)
    price = models.IntegerField()

我的观点:

class Myview(DetailView):
    queryset = product.objects.all()
    template_name = 'templates/products.html'

我的网址:

urlpatterns = [
    url(r'^products/', Myview.as_view(), name='products'),
   ]

如果有任何其他合法的方式从我的模型中获取数据,我可以正确地更改我的视图和网址。

【问题讨论】:

    标签: python django


    【解决方案1】:

    Generic DetailView 用于获取有关模型的单个实例的信息。

    由于您正在获取所有products(在product.objects.all() 行中),因此您似乎想要显示产品列表。在这种情况下,您必须使用ListView

    class MyView(ListView):
        model = Product
        template_name = 'templates/products.html'
    

    【讨论】:

      【解决方案2】:

      在 URL 中你必须传递 pk 作为参数来获取元素

      url(r'^products/(?P<pk>\d+)/$', Myview.as_view(), name='products'),

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-07
        • 2014-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-25
        相关资源
        最近更新 更多