实际上我尝试获取产品详细信息,但是当我转到127.0.0.1:8000/mobiles/motorola-moto-g-16gb时,它正在加载模板但没有显示任何内容,甚至没有显示任何内容错误。
注意:'手机'是url中的类别,休息是您可以看到的产品型号中的slug。
models.py
from django.db import models
from django.utils.text import slugify
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
def __unicode__(self):
return self.name
class Product(models.Model):
title = models.CharField(max_length=140)
slug = models.SlugField(null = True, blank = True)
imgurl = models.CharField(max_length=500)
price = models.CharField(max_length=100)
category = models.ForeignKey(Category)
def save(self, *args, **kwargs):
if not self.id:
self.slug = slugify(self.title)
super(Product, self).save(*args, **kwargs)
def __unicode__(self):
return self.title
views.py
from django.shortcuts import render_to_response, get_object_or_404, Http404
from django.template import RequestContext
from cat.models import Category, Product
def detail(request, slug, category_name_url):
try:
category = Category.objects.get(name=category_name_url)
product = Product.objects.get(slug=slug)
except Product.DoesNotExist:
raise Http404
return render_to_response('product/detail.html', {'product': product, 'category_name': category_name_url})
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from cat import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<category_name_url>\w+)/$', views.category, name='category'),
url(r'^(?P<category_name_url>\w+)/(?P<slug>[-\w]+)$', views.detail , name='detail'),
)
产品/ detail.html
<h1>{{ object.title }}</h1>
<p> {{ object.price }}</p>
<img src="{{ object.imgurl }}">
答案 0 :(得分:2)
因为你正在传递&#39;产品&#39;在您的环境中,您必须使用&#39; product&#39;在你的模板中。
return render_to_response('product/detail.html', {'product': product, 'category_name': category_name_url})
因此,模板代码应为:
<h1>{{ product.title }}</h1>
<p> {{ product.price }}</p>
<img src="{{ product.imgurl }}">