Open mahfujul-helios opened 2 months ago
Django Views are one of the vital participants of MVT Structure of Django. As per Django Documentation, A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, anything that a web browser can display.
Django views are part of the user interface — they usually render the HTML/CSS/Javascript in your Template files into what you see in your browser when you render a web page. (Note that if you’ve used other frameworks based on the MVC (Model-View-Controller), do not get confused between Django views and views in the MVC paradigm. Django views roughly correspond to controllers in MVC, and Django templates to views in MVC.)
Django View Example
Illustration of How to create and use a Django view using an Example. Consider a project named geeksforgeeks having an app named geeks.
After you have a project ready, we can create a view in geeks/views.py,
# import Http Response from django
from django.http import HttpResponse
# get datetime
import datetime
# create a function
def geeks_view(request):
# fetch date and time
now = datetime.datetime.now()
# convert to string
html = "Time is {}".format(now)
# return response
return HttpResponse(html)
Let’s step through this code one line at a time:
For more info on HttpRequest and HttpResponse visit – Django Request and Response cycle – HttpRequest and HttpResponse Objects
Let’s get this view to working, in geeks/urls.py,
from django.urls import path
# importing views from views..py
from .views import geeks_view
urlpatterns = [
path('', geeks_view),
]
Now, visit http://127.0.0.1:8000/,
To check how to make a basic project using MVT (Model, View, Template) structure of Django, visit Creating a Project Django.
Django views are divided into two major categories:-
Function based views are written using a function in python which receives as an argument HttpRequest object and returns an HttpResponse Object. Function based views are generally divided into 4 basic strategies, i.e., CRUD (Create, Retrieve, Update, Delete). CRUD is the base of any framework one is using for development.
Let’s Create a function-based view list view to display instances of a model. Let’s create a model of which we will be creating instances through our view. In geeks/models.py,
# import the standard Django Model
# from built-in library
from django.db import models
# declare a new model with a name "GeeksModel"
class GeeksModel(models.Model):
# fields of the model
title = models.CharField(max_length = 200)
description = models.TextField()
# renames the instances of the model
# with their title name
def __str__(self):
return self.title
After creating this model, we need to run two commands in order to create Database for the same.
Python manage.py [makemigrations](https://www.geeksforgeeks.org/django-app-model-python-manage-py-makemigrations-command/)
Python manage.py [migrate](https://www.geeksforgeeks.org/django-manage-py-migrate-command-python/)
Now let’s create some instances of this model using shell, run form bash,
Python manage.py shell
Enter following commands
>>> from geeks.models import GeeksModel
>>> GeeksModel.objects.create(
title="title1",
description="description1").save()
>>> GeeksModel.objects.create(
title="title2",
description="description2").save()
>>> GeeksModel.objects.create(
title="title2",
description="description2").save()
Now if you want to see your model and its data in the admin panel, then you need to register your model. Let’s register this model. In geeks/admin.py,
from django.contrib import admin
from .models import GeeksModel
# Register your models here.
admin.site.register(GeeksModel)
Now we have everything ready for the back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/
Let’s create a view and template for the same. In geeks/views.py,
from django.shortcuts import render
# relative import of forms
from .models import GeeksModel
def list_view(request):
# dictionary for initial data with
# field names as keys
context ={}
# add the dictionary during initialization
context["dataset"] = GeeksModel.objects.all()
return render(request, "list_view.html", context)
Create a template in templates/list_view.html,
<div class="main">
{% for data in dataset %}.
{{ data.title }}<br/>
{{ data.description }}<br/>
<hr/>
{% endfor %}
</div>
Let’s check what is there on http://localhost:8000/
Similarly, function based views can be implemented with logics for create, update, retrieve and delete views. Django CRUD (Create, Retrieve, Update, Delete) Function Based Views :-
Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views:
Class based view Example – In geeks/views.py,
from django.views.generic.list import ListView
from .models import GeeksModel
class GeeksList(ListView):
# specify the model for list view
model = GeeksMode
Now create a URL path to map the view. In geeks/urls.py,
from django.urls import path
# importing views from views..py
from .views import GeeksList
urlpatterns = [
path('', GeeksList.as_view()),
]
<ul>
<!-- Iterate over object_list -->
{% for object in object_list %}
<!-- Display Objects -->
<li>{{ object.title }}</li>
<li>{{ object.description }}</li>
<hr/>
<!-- If objet_list is empty -->
{% empty %}
<li>No objects yet.</li>
{% endfor %}
</ul>
Let’s check what is there on http://localhost:8000/
Prerequisites: Views in Django In Django, views are Python functions which take a URL request as parameter and return an HTTP response or throw an exception like 404. Each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL configuration)
Let the project name be myProject. The Python module to be used as URLConf is the value of ROOT_URLCONF in myProject/settings.py. By default this is set to 'myProject.urls'. Every URLConf module must contain a variable urlpatterns which is a set of URL patterns to be matched against the requested URL. These patterns will be checked in sequence, until the first match is found. Then the view corresponding to the first match is invoked. If no URL pattern matches, Django invokes an appropriate error handling view.
Including other URLConf modules It is a good practice to have a URLConf module for every app in Django. This module needs to be included in the root URLConf module as follows:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('books.urls')),
]
This tells Django to search for URL patterns in the file books/urls.py.
URL patterns
Here’s a sample code for books/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('books/<int:pk>/', views.book_detail),
path('books/<str:genre>/', views.books_by_genre),
path('books/', views.book_index),
]
For example,
Here, int and str are path convertors and capture an integer and string value respectively.
Path convertors: The following path convertor types are available in Django
Django Views and URL Routing
Views
Views in Django are responsible for handling the business logic and processing HTTP requests and responses. They act as the controller in the Model-View-Template (MVT) architecture. Views can perform various tasks such as querying the database, processing form data, implementing business logic, and rendering templates.
The main responsibilities of views include:
Views can be defined as Python functions or class-based views, providing flexibility in how the application logic is organized and structured.
URL Routing
URL routing in Django maps URL patterns to the corresponding views. It determines which view should handle a particular HTTP request based on the URL path. The URL routing system is defined in the
urls.py
files, which contain patterns that associate URLs with views.Each URL pattern consists of a regular expression and a reference to a view function or class-based view. When a user requests a specific URL, Django's URL routing system matches the URL against the defined patterns and calls the associated view to handle the request.
URL routing in Django serves several purposes:
By separating the concerns of URL routing and view logic, Django promotes a modular and maintainable codebase, allowing developers to focus on implementing the application's functionality without worrying about the low-level details of HTTP request handling and URL parsing.