add category view url with id instead of slug to make BlogCategory.get_absolute_url() work in any case

This commit is contained in:
Tadas Dailyda 2015-02-13 17:30:20 +00:00
parent 2c2fd6d7ca
commit 2288d81659
4 changed files with 24 additions and 4 deletions

View file

@ -15,12 +15,12 @@ class BlogCategoryMenu(CMSAttachMenu):
def get_nodes(self, request):
nodes = []
qs = BlogCategory.objects.translated(get_language())
qs = qs.order_by('parent_id', 'translations__name').distinct()
qs = qs.order_by('parent_id', 'translations__name')
for category in qs:
kwargs = { 'category': category.slug }
node = NavigationNode(
category.name,
reverse('djangocms_blog:posts-category', kwargs=kwargs),
category.get_absolute_url(),
category.pk,
category.parent_id
)

View file

@ -49,6 +49,16 @@ class BlogCategory(TranslatableModel):
def count(self):
return self.blog_posts.filter(publish=True).count()
def get_absolute_url(self):
slug = None
lang = get_language()
if self.has_translation(lang):
slug = self.safe_translation_getter('slug', language_code=lang)
if slug is not None:
return reverse('djangocms_blog:posts-category', kwargs={'category':slug})
# fallback to url with id in case there is no translation of slug
return reverse('djangocms_blog:posts-category-id', kwargs={'category_id':self.pk})
def __str__(self):
return self.safe_translation_getter('name')

View file

@ -15,6 +15,7 @@ urlpatterns = patterns(
url(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<slug>\w[-\w]*)/$', PostDetailView.as_view(), name='post-detail'),
url(r'^author/(?P<username>[\w\.@+-]+)/$', AuthorEntriesView.as_view(), name='posts-author'),
url(r'^category/(?P<category>[\w\.@+-]+)/$', CategoryEntriesView.as_view(), name='posts-category'),
url(r'^category_id/(?P<category_id>\d+)/$', CategoryEntriesView.as_view(), name='posts-category-id'),
url(r'^tag/(?P<tag>[-\w]+)/$', TaggedListView.as_view(), name='posts-tagged'),
url(r'^tag/(?P<tag>[-\w]+)/feed/$', TagFeed(), name='posts-tagged-feed'),
)

View file

@ -133,12 +133,21 @@ class CategoryEntriesView(BaseBlogView, ListView):
@property
def category(self):
if not self._category:
self._category = BlogCategory.objects.active_translations(get_language(), slug=self.kwargs['category']).latest('pk')
if 'category' in self.kwargs:
self._category = BlogCategory.objects.active_translations(get_language(), slug=self.kwargs['category']).latest('pk')
else:
self._category = BlogCategory.objects.get(pk=self.kwargs['category_id'])
return self._category
def get(self, *args, **kwargs):
# submit object to cms toolbar to get correct language switcher behavior
if hasattr(self.request, 'toolbar'):
self.request.toolbar.set_object(self.category)
return super(CategoryEntriesView, self).get(*args, **kwargs)
def get_queryset(self):
qs = super(CategoryEntriesView, self).get_queryset()
if 'category' in self.kwargs:
if 'category' in self.kwargs or 'category_id' in self.kwargs:
qs = qs.filter(categories=self.category.pk)
return qs