class FourDigitYearConverter:
regex = "[0-9]{4}"
def to_python(self, value):
return int(value)
def to_url(self, value):
return '%04d' % value
from django.urls import path, registe_converter
from . impor converters, views
register_converter(converters.FourDigitYearConverter, 'yyyy')
urlpatterns = [path('articles/2003/', views.special_case_2003),
path('articles/<yyyy:year>', views.year_archive)]
from django.urls import path, re_path
from . import views
urlpatterns = [
path('articles/2003/', views.special_case_2003),
re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<slug>[\w-]+)\$', views.article_detail)]
from django.urls import re_path
urlpatterns = [
# bad
re_path(r'blog/(page-(\d+)/)?$', blog_articles),
# good
re_path(r'comments/(?:page-(?P<page_number>\d+)/)?$', comments)]
from django.urls import path
from . import views
urlpatterns = [path('articles/<int:year>/', views.year_archive, name='news_year_archive')]
from django.urls import path
from . import views
urlpatterns = [path('articles/<int:year>/', views.year_archive, name='news-year-archive')]
<a href="{% url 'news-year-archive' 2012 %}">2012 Archive</a>
{# Or with the year in a template context variable: #}
<ul>
{% for yearvar in year_list %}
<li><a href="{% url 'news-year-archive' yearvar %}">{{ yearvar }} Archive</a></li>
{% endfor %}
</ul>
from django.http import HttpResponseRedirect
from django.urls import reverse
def redirect_to_year(request):
# ...
year = 2006
# ...
return HttpResponseRedirect(reverse('news-year-archive', args=(year,)))