Skip to content

Instantly share code, notes, and snippets.

@jonearley
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonearley/caf879bddcd46878db2b to your computer and use it in GitHub Desktop.
Save jonearley/caf879bddcd46878db2b to your computer and use it in GitHub Desktop.
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