Django’s views

Views and the clear project structure that Django offers

Nahuel Molina | Silvio
5 min readNov 16, 2021

Django’s view is a feature that distinguish this framework from others. It confused me the first time, I thought views refers to templates when it actually stands for controllers, like Laravel does. We can say the lingo used by an specific framework produce a delay at switching to other.

Fundamentally, what I noticed when look at Django for the first time, was its simplicity in the project structure. The way that routing and its corresponding controllers are organized shows the process flow. The way that serializers and forms are integrated in the core process is clear. I mean it’s a framework, the main idea is to make the development base simpler, leading the programmer to be entirely focused on the “creative" part of the project, what differentiate a backend project from others.

Other aspect is that each application are created and placed at the root of the project, pointing to the scalability of the site.

There is a mechanism that Django executes each time you point to an URL, looking for a particular service. A function (called view) is asociated to each URL, and it’s triggered once we called that URL.

Types of views

Django can be used to build a microservice or a monolithic application. The first one is an encapsulated application focused on receiveing data, processing inputs and returning data. It’s an API. Django helps to create a backend application that communicates with a frontend (for example a React app), implementing a stateless service avoiding contact with user’s credentials and working with JSON web tokens.

The monolithic application is “simpler”. It is a unique service that contains the backend and also the frontend. Django offers an easy template management. The sessions are keep alive, avoiding the injection of JWT at each request like microservices do. Once a user logs in, he can communicate directly with the backend. Encapsulation in this type of implementations can complicate the scalability, which is a field that microservice stands out. However, at the same time monolithics bring the sufficient functionalities and avoid unneccessary complexities in projects that won’t scale as they say it will. Some companies are regressing in their microservice deployments. But that is a market approach.

Wether you like functions or classes, there’s not a problem because Django gives both possibilities:

  • Function views

A simple function responsible to manage a request object and to return an apropiate response. Django has multiple pre-built responses for different cases. When received data does not comply a certain condition we can return a corresponding error response like 404 objects. If we are working with JSON outputs, wether it is an autentication API or just a service API where we bring a service through using our databases, we can use the JsonResponse object.

It is mandatory to identify the HEADERS in the request. In the case of POST request, we will manage data. With a GET type in majority of cases we render a HTML (django tyep template).

  • Class based views

Django bring us built-in classes to inherits from. You can start building your own view from ListView, intuitively made for listing data from backend like database‘s. We create a dictionary that will hold data retrieved from our database, and finally, the dictionary is injected to a specific HTML django template.

There’s more specific views like TemplateView and AboutView that shorten the function’s building time, making little changes.

Api views

Dispite I mentioned Django can create microservice, it is also limited at that in some aspects. For connecting a frontend app with a backend one, it is mandatory to deploy an API REST traditionally. Today exists alternatives besides this technology, but the goal do not changes: to permit the data transmission between browsers and servers, simplifying various services like authentication and database employment. At least for me it fulfills the main conditions and satisfy my necessities.

Here, django_rest_framework makes its entry. This library works with Django, extending its functionalities, providing a better way to receive and return information. This provides specific and general views, serializers, decorators that are focused on API development. Some of them I will list below:

Generics views

Generics is a library class, that you want to inherit from your classes, in moments you just need to do an specific function. This provides of generics.ListCreateApiView class or generics.ListApiView among others, whose roles are evident in our system. Its unique task is to call the corresponding serializers, which cotains create or list methods or both, they bear with the rest.

ViewSets

viewsets.Viewset has the role of provide us legible methods like create, list, destroy, etcetera.

Even custom methods can be implemented using an special decorator, action, which mark an specific method inside our class to respond for an HTTP method.

APIViews

These views are more customizable, utilizing the fundamental HTTP methods like post, get and others. This is my preferred. Avoiding presumptions and allowing us to modify our code according to our necessities.

As APIs are based on data transfer, you should not response with a simple HTTP response. DRF offers its own response objects for these specific cases. The example I mentioned before is JsonResponse. Along the porjects I prefer to make responses with traditional HTTP format, mixing thing from both the API framework and the lifelong Django.

A little bit more about APIs

As you will see, the logic can be in the view or in the serializer in any case of view you chose. It enables us to add an extra security or verification instance, in terms of managing formats and requirements in our fields when it is about entering data from the frontend. Personally, I have found a taste in data exchange, it is more funny at integrating cookies, cache and tokens in my app than just rendering things from home and send them through the whole internet. Or maybe I just went to the backend side as years go by.

It is easier to work in a project if we take the needed time for spliting its parts, and dedicate a certain period of time to each one. Our brain will reward us not to mention it increase productivity. I payed more attention at security, CSRF and authentication tokens, cache servers like redis or memcached. It is inevitable you will reach your site’s better performance, it is about time.

Naturally, APIs development points to improve our modulation and security threats, serializers and forms are a clear case of that intention in Django apps. They aim to separate our code in different stages, and this way to have a better perspective on what is happening in our project. Make changes, propose new things, and mainly to learn more deeply this beautiful frame. And remember KISS!

--

--

Nahuel Molina | Silvio

This place is what I need for writing about programming, learning in general, and for reading people's thoughts