DEV Community

pooyaalamdari
pooyaalamdari

Posted on • Updated on

django

Django7learn at$ source venv/bin/activate

structure

blog-urls.py

    path('list/', post_list),
    path('archive/<int:year>', post_list),
    path('archive/<int:year>/<int:month>', post_list),
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

Image description
Image description

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
Enter fullscreen mode Exit fullscreen mode
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),
]
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

another way:
blog-urls.py

from django.urls import path, re_path

re_path(r"archive/(?P<year>[0,9]{4})/", post_list),

Enter fullscreen mode Exit fullscreen mode

Top comments (0)