Django slug and id as URL redirection

I have been trying to get something in Django, for hours now, but to no avail. However, I am trying to use friendly URLs such as "my-post-title-1234", where the number at the end is the identifier of the message and rest before it is the name of the message. I got the url using slug and id, and I can get them as in the view. So I check if the identifier exists, and if it exists, I do the rest, and if it does not exist, I do 404 DoNotExist. Inside the model, I created a slug field and a slugified title.

Everything still works, except for one thing: the user can write bla-bla-bla-1234, and he will still show him the same data (since id exists). I would like to:

If the user enters "bla-bla-bla-1234", I would like to redirect him to fix "my-post-title-1234".

This is what my url looks like:

url(r'^(?P<slug>[-\w\d]+)-(?P<post_id>\d+)/$', views.post, name='post')

This is my model:

class Post(models.Model):
    post_title = models.CharField(max_length = 125)
    text = models.TextField()
    slug = models.SlugField(null = False, blank = True)
    def __str__(self):
        return self.post_title
    def save(self, *args, **kwargs):
        self.slug = slugify(self.post_title)
        super(Post, self).save(*args, **kwargs)

This is from my view:

def post(request, slug, post_id):
    try:
        post = Post.objects.get(id = post_id)
    except Post.DoesNotExist:
        raise Http404("Post does not exist")
    return HttpResponse(post_id)

So the question is how to redirect (change the url) to fix the slug from "bla-bla-bla-1234" to "my-post-title-1234" if the user enters slug incorrectly and id is still good ,

Many thanks.

+4
source share
1 answer

It looks like you just need to check the correctness of the bullet and if not to redirect.

from django.shortcuts import get_object_or_404, redirect

def post(request, slug, post_id):
    obj = get_object_or_404(Post, pk=post_id)
    if obj.slug != slug:
        return redirect('post', slug=obj.slug, post_id=obj.pk)

, : get_object_or_404. , , , , ; ( obj ).

+5

Source: https://habr.com/ru/post/1611315/


All Articles