Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'),
    )
like image 595
eagertoLearn Avatar asked Nov 02 '25 02:11

eagertoLearn


1 Answers

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")
]
like image 139
Harry Moreno Avatar answered Nov 03 '25 16:11

Harry Moreno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!