What is view in Django?

A view is defined as a callable that accepts a web (HTTPRequest) request and returns a response (HTTPResponse). It is usually a python function or a python class with a special class method such as as_view().

Views typically does one or more things:

  • Returns plain text response
  • Returns HTML templates or any other formatted text.
  • Raises Exception
  • Talks to database via models

In Django, There are two types views:

  1. Function Based Views (FBV)
  2. Class Based Views (CBV)

In this article, We will discuss about only Function Based Views (FVB).

Here is what a simple view looks like:

# In views.py
from django.http import HttpResponse


def function_view(request): 
       return HttpResponse("Hello World")

Now we can call this function by hitting a URL.

my_project/urls.py.

There is another way of configuring URLs. We will discuss it later.

from django.urls import path
from first_app.views import function_view
  
app_name = 'first_app'

urlpatterns = [
    path('function-view',function_view, name = 'function-view'),
]

Run your server and go to this url: 127.0.0.1:8000/function-view You will see the output…

We can render a whole template through a view. We will use ‘render’ function to do that.

from django.shortcuts import render

def function_view(request):
    return render(request, 'new_template.html')

Now, if we refresh the URL; Django will show an Exception; saying that “TemplateDoesNotExist”

Django is telling us that it is not finding the template named “new_template.html”. We will show Django the direction of our template folder. First create a directory named ‘templates’ inside base directory.

Now, we will have to set the template directory inside our settings.py file. Create a constant named TEMPLATE_DIRS under the BASE_DIR. Add the value “os.path.join(BASE_DIR, ‘templates’)” with the key “DIRS” inside the dictionary of TEMPLATES list.

We can directly set the value with the “DIRS” key. Like that,

Okey, all set to go. Now create an empty template file named ‘new_template.html’ inside templates folder.

Refresh your URL and you will see that the error has been solved but there is nothing on the screen because our “new_template.html” file is empty. So, add some html codes inside the file and see the output.

Output

We’ve come a long way. Now, we will see how Django views talk to the models and how data are fetched from database. We will see how data can be passed into a template.

We have shown the creation of models & created some named “Person”, “PersonsProfile”, “Car” and discussed the mechanisms of querying. Now, we will use those in our views.

def function_view(request):
    person_object = Person.objects.get(id=1)

    context = {
        'person':person_object,
    }
    return render(request, 'new_template.html’, context)

{{ person.first_name }} these are django templates. We’ve discussed in details about Django templates here.

Output

We can also pass additional arguments to this function. These arguments can be captured from parts of the URL or set to default values.

View

def function_view(request,person_id):
    person_object = Person.objects.get(id=person_id)

    context = {
        'person':person_object,
    }
    return render(request, 'new_template.html',context)

We have passed another argument named ‘person_id’ which will be passed from our URL. We have brought our person object by ‘person_id’

URL:

path('function-view/<int:person_id>',function_view,        name='function-view'),

if we hit our URL now, we can see the person’s data whose ‘id’ is passed. Thus, we can make a fully dynamic view.

+ posts

Author | Python-Django Developer

+ posts

Full-stack Developer (Python | Django | React | React-Native | Angular | Vue)