Django – urls.py

Jeff P
1 min readDec 10, 2023

--

Cheat sheet

  1. Import Necessary Modules:
from django.urls import path, re_path, include

2. path() is used for almost all URL patterns:

path('route/', view_function, name='name_of_url')

3. Include urls from other apps in your project

path('app_name/', include('app_name.urls'))

4. Assigning names to url patterns For easy referencing

path('route/', view_function, name='name_of_url')

5. Passing parameters to Django views

path('route/<int:param>/', view_function, name='name_of_url')

6. Avoid conflicts with app_name namespaces

app_name = 'app_name'
urlpatterns = [
# ...
]

7. URL pattern order

URL patterns are matched in the order they appear, so place more specific patterns before generic “Catch-all” ones.

8. Catch-all for homepages

from django.urls import path
from . import views

urlpatterns = [
path('', views.home_view, name='home'),
]

9. Trailing slashes

By default, Django automatically appends a trailing slash to URLs. Use APPEND_SLASH = False in settings.py to disable this behavior.

10. Using Django’s Built-in Views:

By default, ListView retrieves all objects of the specified model:

from django.views.generic import ListView
from .models import Article

class ArticleListView(ListView):
model = Article
template_name = 'article_list.html' # Define the template for displaying the list of articles
context_object_name = 'articles' # Define the variable name for the list of objects in the template
paginate_by = 10 # Specify the number of items to display per page

--

--

Jeff P
Jeff P

Written by Jeff P

I tend to write about anything I find interesting. There’s not much more to it than that really :-)

No responses yet