Django7learn at$ source venv/bin/activate
blog-urls.py
path('list/', post_list),
path('archive/<int:year>', post_list),
path('archive/<int:year>/<int:month>', post_list),
blog-views.py
if month should come before if year
def post_list(request, year=None, month=None):
if month is not None:
return HttpResponse(f"post list archive for {year} and {month}")
if year is not None:
return HttpResponse(f"post list archive for {year}")
return HttpResponse("Posts list page")
create utils.py in blog app
class FourDigitYear:
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, register_converter
from blog.utils import FourDigitYear
from blog.views import post_list, categories_list, post_detail
register_converter(FourDigitYear, 'fourdigit')
urlpatterns = [
path('list/', post_list),
path('archive/<int:year>', post_list),
path('archive/<fourdigit:year>/<int:month>', post_list),
path('detail/<slug:post_slug>/', post_detail),
path('categories/list', categories_list),
]
another way:
blog-urls.py
from django.urls import path, re_path
re_path(r"archive/(?P<year>[0,9]{4})/", post_list),
Top comments (0)