Django 3 : Routing and Creating our first view
Routing in Django
Step 1 : In the previous post, we edited the settings.py file to configure our Django project.
ROOT_URLCONF = 'myproject.urls'
This parameter will define the Python file that will contain all the URLs of our site.
When the controller receives the client request, it will go in the urls.py file and check whether the URL is a customer's request and use the corresponding view.
Step 2 : This is what the urls.py file looks like, as it is created by Django when creating the project:
from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ]
Step 3 : We will have to use the runserver command, We must launch the command prompt and put ourselves in the project root (use the cd command to browse folders) to execute the command:
manage.py runserver 127.0.0.1:8000
Step 4 : To see the result, we must open our browser and enter the following URL: http://localhost:8000
This message also means that we have no specified URL.
Creating our first view
Step 5 : Now in the myproject directory, create the views.py file
from django.http import HttpResponse def index (request) : return HttpResponse ("Hello world!" )
Creating our first URL
Step 6 : We will add two URLs to urls.py file:
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.index), ]
Testing our application
Step 7 : Let's go back to our browser and refresh the page with the F5 key