how to redirect a url with pk to url with pk and slug in django?

巧了我就是萌 提交于 2020-05-13 07:38:53

问题


when a user enters this url below

www.example.com/1234

he must be redirected to

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

For example, if you try this:

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

you will be redirected to

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

Actually it is not a redirect, it is just extending the url with slug fieldautomatically.

I want to implement this feature: Here is my models

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

Here is my urls.py inside my app

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'),
    )

回答1:


Just add another view that gathers the info and redirects:

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))

Then wire it up in your 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'),
    )



回答2:


This is actually a redirection, for SEO purpose. You need to create a view, based on RedirectView and redirect the user to the page with the 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'),
)



回答3:


In case someone comes across this. I wanted to simply redirect and pass in the pk as a keyword argument. Say we have an Article model

# 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")
]


来源:https://stackoverflow.com/questions/23817396/how-to-redirect-a-url-with-pk-to-url-with-pk-and-slug-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!