2011-11-02 63 views
0
article = get_object_or_404(Article,slug=slug) 
categories = article.category.all() 

使用render_to_response(),如何在視圖中使用類別?訪問多對多的值Django

回答

1

假設你已經在模板中的文章,你可以做到以下幾點:

# In your view 
return render_to_response('page.html', {'article': article}) 

# In your template 
{% for category in article.category.all %} 
    {{ category.attribute }} 
{% endfor %} 

# Or, if you already have the categories 
return render_to_response('page.html', {'categories': categories}) 
{% for category in categories %} 
    {{ category.attribute }} 
{% endfor %} 
+0

謝謝,其實我想遍歷的對象,但它說,對象不是可迭代。現在它的工作..任何猜測我可能出錯了? – Vamsi

+1

你沒有發佈你的代碼,但很可能你沒有'.all',沒有'{%for article.category%}'''。 – jro

+0

你是對的..我沒有使用.all-謝謝.. – Vamsi