Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Self correcting Semantic URL slugs, Stack Overflow style.
Self correcting Semantic URL slugs, Stack Overflow style.
For example, we have obj with pk: 1, title: "Hello World", and slug: "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.slug())
# else, A-OK! :thumps-up:
# if slug doesn't exists, redirect
return redirect("object_detail",, 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.