Django views
What are Django views?
In Django, a view is a Python function that takes a web request and returns a web response. The response can be an HTML page, a redirect, or an HTTP error.
A view is responsible for performing a specific action when a request is made to your Django web application. This could be displaying a list of objects, saving an object to the database, or any other task that is needed to be performed when a request is made to your web application.
Two types of views in Django
Before creating views in Django There are two types of views in Django: function-based views and class-based views.
Function Based Views
Function-based views are the traditional way of writing views in Django. They are simple Python functions that take a request object and return a response object. Here is an example of a function-based view:
Example of How to create function-based views in Django
from django.shortcuts import render
def index_view(request):
return render(request, 'index_template.html')
Function-based views are easy to understand and are a good choice for simple views.
Class-Based views in Django
Class-based views are a more modern way of writing views in Django. They are based on the object-oriented concept of inheritance and allow you to reuse code by defining a base view class and creating subclasses for specific views.
There are different types of class-based views are available for a different purposes.
- Base views. View. TemplateView.
- Generic display views. DetailView. ListView.
- Generic editing views. FormView. CreateView.
- Generic date views. ArchiveIndexView. YearArchiveView.
- Class-based views mixins. Simple mixins. ContextMixin.
- Class-based generic views – flattened index. Simple generic views. View.
You can refer to this article for more details on Django class-based views. We will create a detailed tutorial about Django class-based views and their types in future
Example of Django class-based view
from django.views.generic import View
from django.shortcuts import render
class MyView(View):
def get(self, request):
return render(request, 'my_template.html')
Class-based views are more powerful and flexible than function-based views and are a good choice for more complex views.
Both function-based views and class-based views can be linked to a URL and called when a request is made to that URL. The choice between the two types of views depends on the complexity of the view and the needs of your application.
Next tutorial you will learn about Django URLS
- Age calculator using Javascript, HTML & CSS - October 28, 2023
- Navigation bar using HTML & CSS - October 26, 2023
- Calculator using HTML, CSS & JS - October 26, 2023