DEV Community

Cover image for What are Views in Django?
Sachin Chaurasiya
Sachin Chaurasiya

Posted on • Updated on • Originally published at rrtutors.com

What are Views in Django?

Building Web Application is fun and challenging as well. But why do you want to build a web application? is there any need to do that? Yes, there are Business requirements to building an application and requirements could be anything like build an application for data management, build an application for workflow management, etc.

So how Would you map those Business requirements to your code? let me discuss that. the first thing we do is analyze the requirements and come up with a good architecture that also includes the technology stack that you are going to use.

based on the technology stack we map requirements to code. let say the technology stack that we are going to use also includes Django. so how would one write business logic or map requirements to code in Django? the answer is Django views, Yes you heard right Django Viewswhich is V in the MVT Patterns of Django.

if You don't know what is MVT pattern in Django then you can learn from this article.

MVT patterns of django

So, In this post will discuss Django views.

  • What are Django views
  • What Problem it solves
  • Types of views
  • how to write views in Django

What are Django Views?

Django views are Block of code that contains the specific business logic which Takes a web request ** and returns the **response according to the logic. make sense? if not then no worries will understand it with a simple example.

Let say you want to write a function that takes some arguments and based on those arguments you want to return some specific response. like if arguments equal to that then return this and vice-versa.

Same with Django views you write a function that takes web request as an argument and returns the response, the response could be anything like an HTML web page, 404 Error, or an image.

What Problem it solves?

Django views let you map your business logic into the block of code or the function, where you can define what to return? when to return? whom to return?. also it can contain logic related to databases like Reading, writing, updating and deleting. so, basically in these block of code, or functions, you can write whatever different functionality you wanted to.

Types of views in Django

Basically, there are two types of views in Django Function-based and class-based views. both of them have their own use cases and when to use which one is still one of the most asked questions in the Django community, so would not do the same it totally depends on developer and business requirements.

django admin interface.png

Function-based views

Function-based views are nothing but a function that takes the Web request and return the response.
Most people preferred this type of view because they like functional programming and it also more open like whatever we are writing we know what each line of code for.

Classe-based views

Class-based views are based on Object-Oriented Programming(OOP) and come with some abstraction. but Class-based views are reusable with the help of inheritance which is also of the concept of OOP. by using it you can structure your code better.

How to write Views in Django?

Writing Views in Django is very simple and will write some so that you will get a better understanding of it.

Function-based view

Let say you want to write a view that returns the list of blogs from the database

from Django. shortcuts import render
from .models import Blog

def get_blogs(request):
    template_name="blog_list.html"
    context={}
    blogs=Blog.objects.all()
    context["blogs"]=blogs
    return render(request,template_name,context)

Enter fullscreen mode Exit fullscreen mode

The above function will return all the blogs that are available in the database.

Create one template under the templates folder blog_list.html

 <div class="blog_list">

    {% for the blog in blogs %}.

    <div class="card">
     <div class="card_title">
     {{ blog.title }}
     </div>
     <div class="card_description">
        {{ blog.description }}
     </div>
    <span class="card_link">
      <a href="{{ blog.url }}"></a>
    </span>
   </div>

    {% endfor %}

</div>
Enter fullscreen mode Exit fullscreen mode
from Django. shortcuts import render
from .models import Blog
Enter fullscreen mode Exit fullscreen mode

Django provides the render ** method that takes three arguments **request object, template_name and context or dynamic data. the third one is optional because not every view will contain the database logic.

Now we have the view but how to access it, it's simple you just have to add the view in URL patterns with some path like /blogs/.


urls.py file

from .views import get_blogs

urlpatterns = [
    path('blogs/', get_blogs),
]
Enter fullscreen mode Exit fullscreen mode

If You visit the yoursite.com/blogs/ you will see blogs are listed there.

Class-based view

Let say you want to handle the forms for adding a blog to your site.

A basic function-based view that handles forms may look something like this:

from Django. shortcuts import render, redirect

from .forms import AddBlog

def add_blog(request):
    template_name='add_blog.html'
    context={}
    if request.method == "POST":
        form = AddBlog(request.POST)
        if form.is_valid():
            # perform some operation if form is valid

            return redirect('blogs')
    else:
        form = AddBlog()
        context["form"]=form

    return render(request, template_name , context)

Enter fullscreen mode Exit fullscreen mode

The above function will return a simple form when we make the GET request and When we make The POST request with some data it will check if data is valid then it will redirect us to the blog list page.

A similar class-based view might look like this:

from Django. shortcuts import render, redirect
from Django. views import View

from .forms import AddBlog

class AddBlog(View):
    form_class = AddBlog
    template_name = 'add_blog.html'
    context={}
    def get(self, request, *args, **kwargs):
        form = self.form_class()
        self.context["form"]=form
        return render(request, self.template_name, self.context)

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        self.context["form"]=form
        if form.is_valid():
             # perform some operation if form is valid

            return redirect('blogs')

        return render(request, self.template_name, self.context)
Enter fullscreen mode Exit fullscreen mode

In the above code, you can see we are inheriting the View class from Django. as earlier I said class-based view is better-structured ones here you can see that we have two separate methods one is for GET request and another is for POST request. and these methods come with the View class.
Now we have the view but how to access it, it's simple you just have to add the view in URL patterns with some path like /add/.


urls.py file

from .views import AddBlog

urlpatterns = [
    path('add/', AddBlog.as_view()),
]
Enter fullscreen mode Exit fullscreen mode

As you can see for the class-based view we have to execute the as_view method so that Django treat it as a view.

If You visit the yoursite.com/blogs/ you will see a form for adding a new blog.

Thank You for Reading🙂. If you have any Suggestions or Query then let me know in the comment section.

Top comments (0)