Some problems with the confirmation of the urls in Django views
My models:
Story:
categories = models.ManyToMa开发者_JS百科nyField(Category)
Category: name | slug
My urls:
(r'^(?P<cat_slug>.*)/$', 'news.views.archive_category'),
And in views, I use:
def archive_category(request, cat_slug):
entry = News.objects.get( categories__slug=cat_slug )
return render_to_response('news_archive_category.html', {'entry':entry, })
It has something wrong if I have a story of two or more category. Please help me. Many thanks!
category = Category.objects.filter(slug=cat_slug)#get the category requested
#now get all the entries which have that category
entries = News.objects.filter(categories__in=category)#because of the many2many use __in
edited after comment
What do you want to happen in this circumstance? Are you trying to show a list of all the entries in a category, or just one?
News.objects.get()
will always get a single item, or raise an exception if there are more than one matching the criteria. Either you should use filter()
instead, passing a QuerySet to the template, so you'll need to iterate through; or, add a criteria to your urlconf so that you get the specific entry slug as well, so you only get one object.
精彩评论