0
0
Djangoframework~30 mins

URL namespacing in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
URL Namespacing in Django
📖 Scenario: You are building a Django website with two apps: blog and shop. Each app has its own set of URLs. To keep URLs organized and avoid conflicts, you will use URL namespacing.
🎯 Goal: Create URL configurations for the blog and shop apps with namespaces, then include them in the main project urls.py. This will allow you to refer to URLs by their namespace and name.
📋 What You'll Learn
Create a blog/urls.py file with a URL pattern named post_list.
Create a shop/urls.py file with a URL pattern named product_list.
Add a namespace blog for the blog URLs and shop for the shop URLs.
Include both app URL configurations in the main project/urls.py with their namespaces.
💡 Why This Matters
🌍 Real World
Websites often have multiple apps or sections. Namespacing URLs helps keep them organized and prevents name clashes.
💼 Career
Understanding URL namespacing is essential for Django developers to build scalable and maintainable web applications.
Progress0 / 4 steps
1
Create blog app URL patterns
Create a list called urlpatterns in blog/urls.py with one URL pattern. Use path to map the empty string '' to a view called post_list. Name this URL pattern 'post_list'.
Django
Need a hint?

Use path('', views.post_list, name='post_list') inside urlpatterns.

2
Create shop app URL patterns
Create a list called urlpatterns in shop/urls.py with one URL pattern. Use path to map the empty string '' to a view called product_list. Name this URL pattern 'product_list'.
Django
Need a hint?

Use path('', views.product_list, name='product_list') inside urlpatterns.

3
Add namespaces in main urls.py
In the main project/urls.py, import include and path from django.urls. Create a list called urlpatterns that includes the blog URLs with namespace 'blog' and the shop URLs with namespace 'shop'. Use path('blog/', include(('blog.urls', 'blog'), namespace='blog')) and path('shop/', include(('shop.urls', 'shop'), namespace='shop')).
Django
Need a hint?

Use include with a tuple of (app.urls, app_name) and namespace.

4
Use namespaced URLs in templates
In a Django template, write two links using the {% url %} tag. One link should use the namespaced URL 'blog:post_list' and the other 'shop:product_list'. Use anchor tags with href attributes set to these URLs.
Django
Need a hint?

Use {% url 'namespace:url_name' %} inside href attributes.