Python Django Basics – Routing
In Django, routing is the process of directing HTTP requests to the appropriate view function based on the URL of the request. Routes determine which view function will be called when a specific URL is requested.
How to create a new project with Routes
To create a new Django project with routes, follow these steps:
- Make sure you have Django installed on your machine. If not, you can install it using pip:
- Create a new Django project using the django-admin command:
- Change directory to the newly created project:
- Create a new app within the project:
- Define the routes in the urls.py file within the app:
- Create view functions in the views.py file within the app:
- Map the routes to the view functions in the views.py file:
- Run the development server using the following command:
- Visit the URLs in your browser to see the respective views:
$ pip install django
$ django-admin startproject myproject
$ cd myproject
$ python manage.py startapp myapp
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('about/', views.about, name='about'),
]
from django.shortcuts import render
from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to the home page")
def about(request):
return HttpResponse("About Us")
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('about/', views.about, name='about'),
]
$ python manage.py runserver
That’s it! You have successfully created a new Django project with routes. Now you can start building your web application using Django.