Last active
August 29, 2015 14:20
-
-
Save jonearley/caf879bddcd46878db2b to your computer and use it in GitHub Desktop.
Self correcting Semantic URL slugs, Stack Overflow style.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
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