Django 2.0
Simplified url
routing syntax
Florian Demmer
Django Meetup, 2018-06-19
Past and future
-
urlpatterns_1_11 = [ url(r'^articles/2003/$', views.special_case_2003), url(r'^articles/([0-9]{4})/$', views.year_archive), url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive), ]
-
urlpatterns_2_0 = [ path('articles/2018/', views.special_case_2018), path('articles/<int:year>/', views.year_archive), path('articles/<:year>/', views.year_archive), ]
Path converters
- str - non-empty string, excluding '/', default
- path - non-empty string, including '/'
- int - positive integer
- slug - ASCII letters/numbers, hyphen, underscore
- uuid - formatted UUID lowercase string
but my {4} :(
(?P<year>[0-9]{4})
vs
<int:year>
Custom path converters
class FourDigitYearConverter:
regex = '[0-9]{4}'
def to_python(self, value):
return int(value)
def to_url(self, value):
return '%04d' % value
register_converter(FourDigitYearConverter, 'yyyy')
path('articles/<yyyy:year>/', views.year_archive)
or... why change at all?!
urlpatterns = [
path('articles/2003/', views.special_case_2003),
re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
]
Fun with custom converters
class MyThingConverter(IntConverter):
def to_python(self, value):
try:
return MyThing.objects.get(pk=int(value))
except MyThing.DoesNotExist:
raise ValueError
def to_url(self, value):
return str(obj.pk)
register_converter(MyThingConverter, 'my_thing')
path('things/<my_thing:instance>/', my_things_view)
All the things
-
https://docs.djangoproject.com/en/2.0/topics/http/urls/
-
https://consideratecode.com/2018/05/11/the-hidden-powers-of-custom-django-2-0-path-converters/
-
my twitter: @fdemmer
-
slides: https://slides.com/fdemmer
Django Meetup, 2018-06-19
By Florian Demmer
Django Meetup, 2018-06-19
- 1,126