将slug字段传递给url

时间:2014-02-06 07:23:37

标签: python django django-templates django-views

我正在尝试创建我的模型的详细视图:Product。

但是,我没有得到如何将slug-field传递到url。

这是我的详细视图:

def single_product(request):
    product = get_object_or_404(prods, slug=slug)
    return render_to_response('teste.html', locals(), context_instance=RequestContext(request))

这是我的模特:

class Product(models.Model):
    name = models.CharField(max_length=500)
    #inserir slugify na url do produto
    slug = models.SlugField(max_length=500)
    category = models.ForeignKey(Category)
    image = models.ImageField(upload_to='thumbs/')
    created = models.DateTimeField(auto_now=True, auto_now_add=False)
    updated = models.DateTimeField(auto_now=True, auto_now_add=True)

这就是产品1的slug价值:'kinect-xbox-360' 但是当我尝试运行时:[localhost] / kinect-xbox-360 / 我收到这条消息:

TypeError at /kinect-xbox-360/
'str' object is not callable

1 个答案:

答案 0 :(得分:3)

您需要将slug添加到urls.py中的相应网址。然后,它将作为视图中的参数传递:

<强> urls.py

...
url(r'^product/(?P<slug>[\w-]+)/$', 'views.single_product', name='detail'),
...

read more about the url dispatcher

<强> views.py

def single_product(request, slug):
    product = get_object_or_404(prods, slug=slug)
    return render_to_response('test.html', locals(), context_instance=RequestContext(request))

read more about writing function-based views