当我尝试访问产品型号的详细信息页面时,我收到了该错误。我在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"),
任何人都可以查明我做错了什么吗?
答案 0 :(得分:16)
在视图类上设置slug_field
属性:
class ProductPage(DetailView):
model = Product
slug_field = 'product_slug'
# etc
答案 1 :(得分:5)
我想补充一点,get_object也适用于我们为主键提供不同查找参数的情况
示例,如果我想通过guid获取我的对象,我在URLConf中传递
def get_object(self):
return Product.objects.get(guid=self.kwargs.get("guid"))
答案 2 :(得分:0)
models.py
product_slug = models.SlugField(null=True, blank=True, help_text="Product slug field", db_column="product_slug",
verbose_name="slug product", error_messages={"required": "Enter the slug field"},
unique=True, )
使用下面的正则表达式为pk和slug写一行:
urls.py
url(r'(^products/(?P<pk>\d+)/$)|(^products/(?P<product_slug>\w+)/$)',ProductDetailView.as_view(), name='product-detail-view')
views.py
class ProductDetailView(DetailView):
model = Products
extra_context = {'title': 'products-detail-view'}
pk_url_kwarg = 'pk'
query_pk_and_slug = True
slug_field = 'product_slug'
slug_url_kwarg = 'product_slug'