如果slug不匹配,则重定向url

时间:2015-02-11 21:17:14

标签: django redirect slug

我想使用与SO相同的网址模型。查找是通过id号完成的,但是如果链接中的错误slug,则重定向被抛出到正确的页面。

例如: 问题/ 4787731 /无论将重定向到问题/ 4787731 / canonical-links-and-301-redirect-if-url-doesnt-match-slug。 我当前的代码通过id进行查找,但是在不好的情况下不会重定向。 例: 实体/ 12786676 /无论应该重定向到/ entities / 12786676 / yellow-and-green-tree /。我确实正确地获取了页面的内容,但我也希望重定向URL以避免错误的链接。 这是代码:

的观点:

class EntityRedirectDetailView(RedirectView):
    def get(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk', None)
        slug=self.kwargs.get('slug', None)
        entity = EntitiesNew.objects.get(pk=pk)
        self.url = '/entities/%s/%s' % (entity.pk, entity.slug)
        return super(EntityRedirectDetailView, self).get(request, *args, **kwargs)

网址:

urlpatterns = [
    url(r'^$', ListView.as_view(context_object_name = 'entities_list', queryset=EntitiesNew.objects.order_by('-id_number')[:500]), name='entities'),  
    url(r'^(?P<pk>\d+)/$', views.EntityRedirectDetailView.as_view(), name='entities-redirect'),  
    url(r'^(?P<pk>\d+)(?:/(?P<slug>[\w\d-]+))?/$', DetailView.as_view( model=EntitiesNew, context_object_name="entity"), name="entities-detail"),
]

感谢

1 个答案:

答案 0 :(得分:0)

好的,我按照Paulo Almeida的建议覆盖了我的EntityDetailView(Detailview)中的get方法,设法做了我想做的事。这是最终的代码。

urls.py:

url(r'^(?P<pk>\d+)/$', views.EntityRedirectDetailView.as_view(), name='entities-redirect'), 
    url(r'^(?P<pk>\d+)/(?P<slug>[-\w\d]+)/$', views.EntityDetailView.as_view(), name="entities-detail"),

views.py

class EntityRedirectDetailView(RedirectView):
    def get(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk', None)
        slug=self.kwargs.get('slug', None)
        entity = EntitiesNew.objects.get(pk=pk)
        self.url = '/entities/%s/%s' % (entity.pk, entity.slug)
        return super(EntityRedirectDetailView, self).get(request, *args, **kwargs)

class EntityDetailView(generic.DetailView):
    """
        A DetailView which redirects to the absolute_url, if necessary.
    """
    template_name = 'entities/entitiesnew_detail.html'
    queryset = EntitiesNew.objects.get_queryset()
    def get_object(self, *args, **kwargs):
        # Return any previously-cached object
        pk = self.kwargs.get('pk', None)
        entity=EntitiesNew.objects.get(pk=pk)
        if getattr(self, 'entity', None):
            return self.entity
        return super(EntityDetailView, self).get_object(*args, **kwargs)
    def get(self, *args, **kwargs):
        # Make sure to use the canonical URL
        self.entity = self.get_object()
        obj_url = self.entity.get_absolute_url()
        if self.request.path != obj_url:
            return http.HttpResponsePermanentRedirect(obj_url)
        return super(EntityDetailView, self).get(*args, **kwargs);
在models.py中的

我有get_absoulte_url:

def get_absolute_url(self):
        return reverse('entities:entities-detail', kwargs={'pk':self.pk, 'slug':self.slug})

并在模板中: {%url'entities:entities-detail'entitynew.pk entitiesnew.slug%}