Django - URLs & Views

A URL is a web address. You can see a URL every time you visit a website – it is visible in your browser's address bar. eg: 127.0.0.1:8000 is a URL, And https://docs.djangoproject.com/en/4.0/ is a URL.

Every page on the Internet needs its own URL. This way your application knows what it should show to a user who opens that URL. In Django, we use URLconf (URL configuration) to match the requested URL to find the correct view.

The view is a python function which is used to perform some business logic and return a response to the user. This response can be the HTML contents of a web page, or a redirect a web page, or a 404 error.

Create 'urls.py' in your app.

from django.urls import path
from . import views

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

Define the home function in views.py

from django.shortcuts import render
from django.http import HttpResponse

def home(request):
    return HttpResponse("Hello world")
    #return HttpResponse("Hello world <a href="/">Back</a>")
	

Also add url in your project 'urls.py'

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('hello.urls')),
    path('admin/', admin.site.urls),
]

For every URL, Django will find a corresponding view.

Views - Returning Errors

Django provides various built-in error classes that are the subclass of HttpResponse and use to show error message as HTTP response. Some classes are listed below.

Class Description
class HttpResponseNotModified It is used to designate that a page hasn't been modified since the user's last request (status code 304).
class HttpResponseBadRequest It acts just like HttpResponse but uses a 400 status code.
class HttpResponseNotFound It acts just like HttpResponse but uses a 404 status code.
class HttpResponseNotAllowed It acts just like HttpResponse but uses a 410 status code.
class HttpResponseServerError It acts just like HttpResponse but uses a 500 status code.

Create 'urls.py' in your app.

from django.shortcuts import render  
from django.http import HttpResponse, HttpResponseNotFound  
def index(request):  
    a = 1  
    if a:  
        return HttpResponseNotFound('<h1>Page not found</h1>')
    else:  
        return HttpResponse('<h1>Page was found</h1>')