如何将带有pk的URL重定向到带有pk和django中的slug的url?

时间:2014-05-22 21:30:59

标签: django django-urls http-redirect

当用户在

下输入此网址时
www.example.com/1234

他必须被重定向到

www.example.com/1234/this-is-your-first-post

例如,如果您尝试这样做:

 http://stackoverflow.com/questions/15443306/

您将被重定向到

http://stackoverflow.com/questions/15443306/hover-menu-in-right-side-of-fixed-div

实际上它不是redirect,只是自动将urlslug field一起扩展。

我想实现此功能: 这是我的模特

class Article(models.Model):
    title = models.CharField(max_length=20)
    body = models.TextField()
    # image = models.ImageField(upload_to="/", blank=True, null=True)
    date = models.DateField()
    likes = models.IntegerField()
    slug = models.SlugField()

    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.title)
        super(Article, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('article_detail', kwargs={'slug':self.slug, 'pk':self.id})

    def __unicode__(self):
        return self.title

这是我的应用内的urls.py

urlpatterns = patterns('',
    url(r'all$', ArticleList.as_view(), name='blog_all'),
    url(r'^(?P<pk>\d+)/(?P<slug>[-\w\d]+)/$', ArticleDetail.as_view(), name='article_detail'),
    )

3 个答案:

答案 0 :(得分:3)

只需添加另一个收集信息并重定向的视图:

class ArticleDetailRedirect(RedirectView):

    def get_redirect_url(self, pk):
        article = Article.objects.get(pk=pk)
        slug = article.slug
        return reverse('article_details', args=(pk, slug))

然后将其连接到urls.py

urlpatterns = patterns('',
    url(r'all$', ArticleList.as_view(), name='blog_all'),
    url(r'^(?P<pk>\d+)/$', ArticleDetailRedirect.as_view(), name='article_redirect'),
    url(r'^(?P<pk>\d+)/(?P<slug>[-\w\d]+)/$', ArticleDetail.as_view(), name='article_detail'),
    )

答案 1 :(得分:2)

这是实际上重定向,用于SEO目的。您需要根据RedirectView创建一个视图,并将用户重定向到带有slug的页面:

class ArticleRedirectView(RedirectView):
    """ Will make a HTTP 301 redirection from blog/1/ to blog/1/slug_of_article """
    def get_redirect_url(self, *args, **kwargs):
        article = get_object_or_404(Article, pk=pk)
        return reverse('article_detail', args=(pk, slug))


urlpatterns = patterns('',
    url(r'all$', ArticleList.as_view(), name='blog_all'),
    url(r'^(?P<pk>\d+)/$', ArticleRedirectView.as_view()),
    url(r'^(?P<pk>\d+)/(?P<slug>[-\w\d]+)/$', ArticleDetail.as_view(), name='article_detail'),
)

答案 2 :(得分:0)

万一有人碰到这个。我只想重定向并传入pk作为关键字参数。假设我们有一个Article模型

# views.py
from django.shortcuts import redirect

def article_create(request):
    article_form = ArticleForm(request.POST)
    if article_form.is_valid():
        article = article_form.save()
        return redirect("articleDetail", pk=article.id)

# urls.py
from django.urls import path

urlpatterns = [
    path('article/create', views.article_create, name="articleCreate")
    path('article/<int:pk>', views.article_detail, name="articleDetail")
]