how to redirect a url with pk to url with pk and slug in django?
django, django-urls, http-redirect
Solution
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'),
)
Problem
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 field`automatically. 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'), ) ```