Florian Demmer
Django Meetup, 2018-06-19
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),
]
(?P<year>[0-9]{4})
vs
<int:year>
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)
urlpatterns = [
path('articles/2003/', views.special_case_2003),
re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
]
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)
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