[Fixed]-Clean, name-based urls with class-based views

1πŸ‘

βœ…

Yes, this can be done. I’m giving you one example here.

Define your models:

class State(models.Model):
    slug = models.SlugField()

class City(models.Model):
    slug = models.SlugField()
    state = models.ForeignKey(State)

Define your view:

from django.views.generic import DetailView
from .models import City

class CityDetailView(DetailView):

    def get_object(self):
        city = City.objects.get(
            slug=self.kwargs.get('city'),
            state__slug=self.kwargs.get('state')
        )
        return city

And finally, add this to your urls.py:

from django.conf.urls import url
from .views import CityDetailView

urlpatterns = [
    url(r'^(?P<state>\w+)/(?P<city>\w+)/$', CityDetailView.as_view()),
]
πŸ‘€ozren1983

Leave a comment