Django Views
Overview
Django follows the Model Template View(MVT) architecture. According to Django documentation, the view function is a Python function that takes a web request and returns a web response. The response can be the HTML content of a web page, a 404 error, a redirect, an image, an XML document, etc. It is the user interface, that displays the content of the webpage when we render a website. It is represented by HTML/CSS/Javascript. The view functions are created in the views.py file present inside the folder of each application we create in Django.
Introduction to Django Views
You must be aware of the fact that Django follows an architectural pattern that includes Model, Template, and View. In this article, we will focus on Views in Django. Here in the views.py file, we create a view function and link the HTML file we created. This view function is in turn linked in the urls.py file with the path, as explained in the example in the next section. There are two types of views, function-based view, and class-based view.
Django View Example
Let us consider an example to demonstrate the creation and use of Django View. Let us assume we made a project Glitten having an app world. After the project is ready and the app is created, we can create a view in the views.py file present inside the folder of the app, in our case, it is named World. This file is used to link the HTML, XML or, javascript file to the view function we create so that the contents and information stored in the HTML, XML, etc. can be displayed and made available to the user. In theviews.py file,
In the above code,
- We import the model GlittenModel we created in the models.py file.
- We create a view function first.
- We link the HTML page we created in the template folder with the view function first. In the urls.py file,
In the above code,
- From django.urls we import the path.
- From .views we import the view functions we created.
- Under urlpatterns we link the view function first in the path.
Types of views
Django includes two different types of views:-
- Function-Based Views
- Class-Based Views
1. Function-Based Views
In the function-based view, we use a function in Python which receives the HttpRequest object as an argument and returns an HttpResponse Object in the form of HTML content, 404 error, XML document, etc. Function-based views are divided into four basic strategies (Create, Retrieve, Update, and Delete) CRUD. Let us take an example of a function-based view. In the models.py file, we create the model.
After creating the model we need to run the following commands in the command prompt.
As we know in the above commands, 'makemigrations' is responsible for packing up the changes into individual migration files, and 'migrate' is responsible for applying those to our database. Now to access Django ORM we write the following:
This leads us to an interactive Python console.
In the console, we create objects of the model as shown in the following example.
To see our model and its data in the admin panel we need to register our model in the admin.py file, present inside the folder of the app created.
We can check the created models here Now let us create the view function in the views.py file so that we can connect our HTML page with the view function we create.
In the code above, we imported our model Glitten, after creating a view 'list', we are using a dictionary named context with the title as keys and description as values.
Now a URL path is created to map the view. In the urls.py,
In the folder template, we create an HTML file named list.html which we linked in the view function created above.
We can check it here
2. Class-based View
Class-Based View implements views as Python objects and not as functions. It provides a class instance method as_view(). In each generic view, the as_view() class instance method creates a connection for calling the class as if it were a method. Well, a method is a label that can be applied to an object; it is a piece of code that can be executed on that object. Certain advantages of the same are listed below:
- Code organization related to HTTP methods like GET, POST, etc. can be addressed by separate methods instead of conditional branching.
- In CBV, a view class can be inherited by another view class and modified for a different use case.
A function-based view with a huge number of lines of code can be converted into a class-based view containing few lines only.
Let us take an example of a class-based view. In the views.py file,
Now a URL path is created to map the view. In the urls.py,
It provides a class instance methodas_view(). In each generic view, the as_view() class instance method creates a connection for calling the class as if it were a method. Well, a method is a label that can be applied to an object; it is a piece of code that can be executed on that object. We create an HTML file named Glitten_list.html,
We can check it here
Writing Views
Let us take an example, we created an app named myapp.
- Create a simple view in myapp In the views.py file,
- We import the class HttpResponse from the Django.http module.
- We also imported Python’s datetime library.
- We define a function named greet. It is a view function, taking an HttpRequest object as its first parameter, named request.
- This view function returns an HttpResponse object that contains the generated response. Each view function returns an HttpResponse object.
- Mapping URLs to views In the urls.py file,
- From django. URLs we import path.
- From .views we import greet, the view function we created.
- Under urlpatterns, we link the view function greet in the path.
Upon visiting the URL http://127.0.0.1:8000/, we see
- Returning errors
Django provides some built-in error classes that are the subclass of HttpResponse and shows the error message as an HTTP response.
In the above code,
- We imported HttpResponse and HttpResponseNotFound from django.http module.
- We created a function named error.
- We are returning a response with a status code 404.
In the urls.py,
- We imported views from the app myapp.
- We linked the view function error in the urls.py file.
Below is the list of subclasses of HttpResponse with their codes and description.
- class HttpResponseNotModified: It specifies that a page hasn't been modified since the user's last request (status code 304).
- class HttpResponseBadRequest: It acts like HttpResponse (status code 400).
- class HttpResponseNotFound: It acts like HttpResponse (status code 404).
- class HttpResponseNotAllowed: It acts like HttpResponse (status code 410).
- class HttpResponseServerError: It acts like HttpResponse (status code 500).
- Django View HTTP Decorators
HTTP Decorators are used to restrict access to views based on the method of request. These decorators are present in django.views.decorators, if conditions are not met it returns a django.http.HttpResponseNotAllowed. The syntax is require_http_methods(request_method_list).
- Django HTTP Decorator Example
In the views.py file,
- We imported HttpResponse and HttpResponseNotFound from django.http.
- We also import require_http_methods from django.views.decorators.http.
- GET in the syntax, @require_http_methods(["GET"]) signifies that the view only accepts the GET method.
- On the other hand, if the syntax was @require_http_methods(["POST"]) then view only would accept the POST method.
In the urls.py file,
- We imported views from the app myapp.
- We linked the view function decor in the urls.py file.
Conclusion
Hello Developer! Well after going through this article you must be having a clear idea about Views in Django. Now let us summarize what we learned from this article
- Django follows Model Template View(MVT) architecture.
- View function is a Python function that takes a web request and returns a web response.
- There are two types of views, function-based view, and class-based view.
- In the function-based view, we use a function in Python which receives the HttpRequest object as an argument and returns an HttpResponse Object.
- Class-Based View implements views as Python objects and not as functions.
- A method is a label that can be applied to an object; it is a piece of code that can be executed on that object.
- Django provides some built-in error classes that are the subclass of HttpResponse and shows the error message as an HTTP response.
- HTTP Decorators restrict access to views based on the request method.