In this lesson, we will explore the structure of Django apps and learn how to configure URL routing. Understanding these concepts is essential for building scalable and maintainable web applications.
A Django project is made up of one or more apps. Each app is a self-contained module that can be reused in different projects. Here’s a typical structure of a Django app:
myapp/
├── migrations/
├── __init__.py
├── admin.py
├── apps.py
├── models.py
├── tests.py
├── views.py
└── urls.py
__init__.py: This is an empty file that tells Python this directory should be treated as a package.URL routing is the process of mapping URLs to views in your Django application. This is done in the urls.py file of your app. Let's look at a simple example.
Here’s how to define URL patterns in urls.py:
# myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('about/', views.about, name='about'),
]
Now, let’s create the corresponding views in views.py:
# myapp/views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to the Home Page!")
def about(request):
return HttpResponse("This is the About Page.")
To make these URLs accessible, you need to include your app’s urls.py in the project’s main urls.py file. Here’s how:
# myproject/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
Avoid hardcoding URL patterns: If you change a URL pattern, make sure to update all references to it in your templates and views.
Neglecting to include app URLs: Always remember to include your app’s URLs in the main project
urls.py.
models.py, views.py, and urls.py.Create a new view in views.py that returns a simple HTML response. Update urls.py to include this new view.
Add a new URL pattern for a contact page in urls.py. Create the corresponding view in views.py that returns a message like "Contact Us!".
Change the URL pattern for the home page to /homepage/ instead of /. Update the urls.py accordingly.