django - 通用详细信息 View 必须使用对象pk或子弹调用

标签 django

当我尝试访问产品模型的详细信息页面时,我收到该错误。我在url文件中有slug字段,但这似乎无关紧要。

模型

class Product(models.Model):
    product_name= models.CharField(max_length=30, blank=False, null=False, verbose_name="the product name")
    product_slug= models.SlugField(max_length=30, blank=False, null=False, verbose_name="the product slug")
    product_excerpt= models.CharField(max_length=100, blank=False, null=False, verbose_name="product excerpt")
    def _set_product_code(self):
        product_code_temp = hashlib.sha224()
        product_hash = self.product_name
        product_hash = product_hash.encode('utf-8')
        product_code_temp.update(product_hash)
        return product_code_temp.hexdigest()[0:5]
product_code = property(_set_product_code)

看法
class ProductPage(DetailView):
    model = Product
    context_object_name = 'product'
    template_name="product.html"

网址
url(r'^product/(?P<product_slug>\w+)/(?P<product_code>\w+)/$', ProductPage.as_view(), name="product"),

谁能指出我做错了什么?

最佳答案

在 View 类上设置slug_field属性:

class ProductPage(DetailView):
    model = Product
    slug_field = 'product_slug'

根据您的URLConf,您可能还需要指定与该段相对应的kwarg的名称。它默认为'slug'。如果您在URL规范中使用了其他内容,例如本示例中的“product_slug”,则还要在 View 上指定slug_url_kwarg属性:
    slug_url_kwarg = 'product_slug'
    # etc

关于django - 通用详细信息 View 必须使用对象pk或子弹调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19407239/

相关文章:

python - 在 Django 中创建了一个新模型。但它没有出现在数据库中

django - 使用远程存储配置 django-compressor (django-storage - amazon s3)

django - 如何为邮政地址建模

python - 创建受密码保护的 zip 文件?

django - 将参数传递给 Django ModelForm clean 方法

django - 如何在没有重复字段的情况下注释字段django

python - 如何在 Django 中自动更改模型字段

python - Django : Two Models from Separate Databases

python - 在多个 session 中更新/选择 mysql 表

python - Django 缓存导致数据库中出现重复键错误?