0
0
Djangoframework~5 mins

Including app URLs in Django

Choose your learning style9 modes available
Introduction

Including app URLs helps organize your website by keeping each app's web addresses separate and easy to manage.

When your project has multiple apps and you want to keep their URLs organized.
When you want to avoid repeating URL patterns in the main project file.
When you want to make your project easier to maintain and scale.
When you want to reuse app URLs in different projects.
When you want to keep your main URL file clean and simple.
Syntax
Django
from django.urls import include, path

urlpatterns = [
    path('appname/', include('appname.urls')),
]

The include() function tells Django to look inside the app's urls.py for more URL patterns.

The string before include() is the URL prefix for all URLs in that app.

Examples
This includes all URLs from the blog app under the URL prefix /blog/.
Django
path('blog/', include('blog.urls'))
This includes all URLs from the shop app under the URL prefix /shop/.
Django
path('shop/', include('shop.urls'))
This includes URLs from the main app at the root URL (no prefix).
Django
path('', include('main.urls'))
Sample Program

This example shows how the main urlpatterns includes URLs from two apps: blog and shop. Each app has its own urls.py and views. Visiting /blog/ shows the blog welcome message, and /shop/ shows the shop welcome message.

Django
from django.urls import path, include

urlpatterns = [
    path('blog/', include('blog.urls')),
    path('shop/', include('shop.urls')),
]

# blog/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='blog-index'),
]

# shop/urls.py
from django.urls import path
from . import views

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

# views.py for blog
from django.http import HttpResponse

def index(request):
    return HttpResponse('Welcome to the Blog!')

# views.py for shop
from django.http import HttpResponse

def home(request):
    return HttpResponse('Welcome to the Shop!')
OutputSuccess
Important Notes

Always create a urls.py file inside each app to define its URL patterns.

Using include() keeps your project URLs clean and easier to read.

Remember to import include from django.urls in your main urls.py.

Summary

Including app URLs helps organize your project by separating URL patterns per app.

Use path('prefix/', include('app.urls')) to add app URLs under a URL prefix.

This makes your project easier to maintain and scale.