Creating a New Project with Routes in Python Django: A Basic Guide to Routing

Posted by

Python Django Basics – Routing

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:

  1. Make sure you have Django installed on your machine. If not, you can install it using pip:

  2. $ pip install django

  3. Create a new Django project using the django-admin command:

  4. $ django-admin startproject myproject

  5. Change directory to the newly created project:

  6. $ cd myproject

  7. Create a new app within the project:

  8. $ python manage.py startapp myapp

  9. Define the routes in the urls.py file within the app:

  10. from django.urls import path
    from . import views

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

  11. Create view functions in the views.py file within the app:

  12. 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")

  13. Map the routes to the view functions in the views.py file:

  14. from django.urls import path
    from . import views

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

  15. Run the development server using the following command:

  16. $ python manage.py runserver

  17. Visit the URLs in your browser to see the respective views:

That’s it! You have successfully created a new Django project with routes. Now you can start building your web application using Django.