Django first view
Prerequisites
Django view
- Django view is a python function or a class that handles HTTP requests/responses.
Django first view.
- open
my_app/views.py
and add the below code to it
from django.http import HttpResponse
def first_view(request):
return HttpResponse("<h1>Hurray!! My first django view</h1>")
- Django view takes the request as parameter and returns the HTTP response.
- Django provides the
HttpResponse
class to create the HTTP response.
- create a new file
my_app/urls.py
and below code to it.
from django.urls import path
from my_app import views
urlpatterns = [
path('', views.first_view, name='first_view'),
]
- Django provides
path
function to map the requested url to the django view based on the request path. - Django looks at
urlpatterns
variable to find the urls.
Congifure app urls to project urls
- Previously, we configured the app urls to view. But, it won't work until we configure it with project urls.
- Project urls are the root urls where the django request recieved based on the url path and dispatched to respective django view.
- To configure the app urls to the project, open file
my_project/urls.py
and update it accordingly.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
# include app urls
path('my_app/', include('my_app.urls')),
path('admin/', admin.site.urls),
]
References: