Pattern order

Order your patterns to take advantage of how Django processes them, that is, top-down. A good rule of thumb is to keep all the special cases at the top. Broader or more general patterns can be mentioned further down. The broadest, a catch-all-if present, can go at the very end.

For example, the path to your Blog posts might be any valid set of characters, but you might want to handle the About page separately. The right sequence of patterns should be as follows:

blog_patterns = [ 
    path('about/', views.AboutView.as_view(), name='about'), 
    path('<slug:slug>/', views.ArticleView.as_view(), name='article'), 
]   

If we reverse the order, then the special case, the AboutView, will never get called.

Get Django Design Patterns and Best Practices - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.