Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Self correcting Semantic URL slugs, Stack Overflow style.
'''
Self correcting Semantic URL slugs, Stack Overflow style.
Format:
website.com/obj/<pk>/<slug>
For example, we have obj with pk: 1, title: "Hello World", and slug: "hello-world"
website.com/obj/1/ -> website.com/obj/1/hello-world
website.com/obj/1/hello-moon/ -> website.com/obj/1/hello-world
'''
from django.views.generic import DetailView
from django.shortcuts import get_object_or_404
from .models import Object
class ObjectDetailView(DetailView):
model = Object
def dispatch(self, request, *args, **kwargs):
obj = get_object_or_404(Object, pk=self.kwargs['pk'])
# if slug exists, continue
if 'slug' in self.kwargs:
# if slug doesn't match, redirect
if obj.slug() != self.kwargs['slug']:
return redirect("object_detail", obj.pk, obj.slug())
# else, A-OK! :thumps-up:
# if slug doesn't exists, redirect
else:
return redirect("object_detail", obj.pk, obj.slug())
return super(ListsDetailView, self).dispatch(request, *args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.