【问题标题】:How do I pass a parameter to views and access all objects?如何将参数传递给视图并访问所有对象?
【发布时间】:2013-06-24 13:38:15
【问题描述】:

我使用 slug 作为 url 的访问点。

http://127.0.0.1:8000/category/blah/ -> blah is the slug. 

这是我的网址代码。

 url(r'^category/(?P<category>[A-Za-z]\w*)/$', individual_category),

这是我的看法

def individual_category(request, category): 

    pro =  get_object_or_404(Product, username= category) -> (This doesnt seem to work ))
    return render_to_response('individual_category.html', {'obs':pro})

这是我的模板

<html>
<body>
<p> The list of products are </p>
<b>{{category}}</b>

{% for items in obs %}

    <li>{{items.category}}</li>
    <li>{{items.title}}</li>
    <img src = "/images/{{items.image}}"</li>   

    <br>
    <br>

{% endfor %}



</body>
</html>

【问题讨论】:

  • This doesnt seem to work...你能说得更具体些吗?
  • 请发布您的产品型号

标签: python django django-models django-views


【解决方案1】:

据我了解您的模型定义,您的查询错误:

pro =  get_object_or_404(Product, username= category) -> (This doesnt seem to work ))

您正在尝试选择用户名与类别相同的产品。现在我不知道你的模型Product 是否有一个字段username(我对此表示怀疑),但我猜你需要过滤category 字段。

但是get_object_or_404 只选择 1 个对象并看到您的模板,这不是您想要的。

我认为你最好使用:

pro = Product.objects.filter(category=category)

如果 category 是一个模型,您需要首先从数据库中获取对象,因此 get_object_or_404 方法将是合适的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    相关资源
    最近更新 更多