Google News
logo
Django Interview Questions
Django is a web development framework that was developed in a fast-paced newsroom. It is a free and open-source framework that was  named after Django Reinhardt who was a jazz guitarist from the 1930s. Django is maintained by a non-profit organization called the Django Software Foundation. The main goal of Django is to enable Web Development quickly and with ease.
Programmers like Django mostly for its convenient features like :
 
* Optimized for SEO
* Extremely fast
* A loaded framework that features authentications, content administrations and RSS feeds
* Exceptionally scalable to meet the heaviest traffic demand
* Highly secure
* Versatility, enabling you to create many different types of websites
Web developers use Django because it :
 
* Allows code modules to be divided into logical groups, making them flexible to change
* Provides an auto-generated web admin module to ease website administration
* Provides a pre-packaged API for common user tasks
* Enables developers to define a given function’s URL
* Allows users to separate business logic from the HTML
* Is written in Python, one of the most popular programming languages available today
* Gives you a system to define the HTML template for your web page, avoiding code duplication
Features available in Django are :
 
* Admin Interface (CRUD)
* Templating
* Form handling
* Internationalization
* Session, user management, role-based permissions
* Object-relational mapping (ORM)
* Testing Framework
* Fantastic Documentation
Django is based on MVT architecture. It contains the following layers :
 
Models : It describes the database schema and data structure.
 
Views : The view layer is a user interface. It controls what a user sees, the view retrieves data from appropriate models and execute any calculation made to the data and pass it to the template.
 
Templates : It determines how the user sees it. It describes how the data received from the views should be changed or formatted for display on the page.
 
Controller : Controller is the heart of the system. It handles requests and responses, setting up database connections and loading add-ons. It specifies the Django framework and URL parsing.
Django Admin is the preloaded interface made to fulfill the need of web developers as they won’t need to make another admin panel which is time-consuming and expensive.
 
Django Admin is application imported from django.contrib packages.
 
It is meant to be operated by the organization itself and therefore doesn’t need the extensive frontend.
 
Django’s Admin interface has its own user authentication and most of the general features.
 
It also offers lots of advanced features like authorization access, managing different models, CMS (Content Management System), etc.
Templates are an integral part of the Django MVT architecture. They generally comprise HTML, CSS, and js in which dynamic variables and information are embedded with the help of views. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags.
 
A template is rendered with a context. Rendering just replaces variables with their values, present in the context, and processes tags. Everything else remains as it is.
 
The syntax of the Django template language includes the following four constructs :
 
* Variables
* Tags
* Filters
* Comments

To read more about templates you can refer to this : https://docs.djangoproject.com/en/4.0/topics/templates/
A view function, or “view” for short, is simply a Python function that takes a web request and returns a web response. This response can be HTML contents of a web page, or a redirect, or a 404 error, or an XML document, or an image, etc. 
 
Example :
from django.http import HttpResponse
def sample_function(request):
 return HttpResponse(“Welcome to Django”)

 

There are two types of views :
 
Function-Based Views : In this, we import our view as a function.
Class-based Views : It’s an object-oriented approach.
To check for the version of Django installed on your system, you can open the command prompt and enter the following command :
 
python -m django –version

You can also try to import Django and use the get_version() method as follows :
import django
print(django.get_version())
Django comes with a default database which is SQLite. To connect your project to this database, use the following commands :
 
* python manage.py migrate (migrate command looks at the INSTALLED_APPS settings and creates database tables accordingly)
* python manage.py makemigrations (tells Django you have created/ changed your models)
* python manage.py sqlmigrate (sqlmigrate takes the migration names and returns their SQL)
Django can be broken into many components :
 
Models.py file : This file defines your data model by extending your single line of code into full database tables and add a pre-built administration section to manage content.
 
Urls.py file : It uses a regular expression to capture URL patterns for processing.
 
Views.py file : It is the main part of Django. The actual processing happens in view.
 
When a visitor lands on Django page, first Django checks the URLs pattern you have created and used the information to retrieve the view. After that view processes the request, querying your database if necessary, and passes the requested information to a template.
 
After that, the template renders the data in a layout you have created and displayed the page.
It has nothing to do with dirt or grime. It’s a handy acronym for Create, Read, Update, and Delete. It’s a mnemonic framework used to remind developers on how to construct usable models when building application programming interfaces (APIs).
Django's disadvantages include :
 
* Its monolithic size makes it unsuitable for smaller projects
* Everything hinges on Django’s ORM (Object-Relational Mapping)
* Everything must be explicitly defined due to a lack of convention
Migration in Django is to make changes to your models like deleting a model, adding a field, etc. into your database schema.  There are several commands you use to interact with migrations.
 
* Migrate
* Makemigrations
* Sqlmigrate

To do the migration in SQL, you have to print the SQL statement for resetting sequences for a given app name.
In Django, there is three possible inheritance styles
 
* Abstract base classes : This style is used when you only wants parent’s class to hold information that you don’t want to type out for each child model

* Multi-table Inheritance : This style is used If you are sub-classing an existing model and need each model to have its own database table

* Proxy models : You can use this model, If you only want to modify the Python level behavior of the model, without changing the model’s fields
Mixin is a type of multiple inheritance wherein you can combine behaviors and attributes of more than one parent class. Mixins provide an excellent way to reuse code from multiple classes. For example, generic class-based views consist of a mixin called TemplateResponseMixin whose purpose is to define render_to_response() method. When this is combined with a class present in the View, the result will be a TemplateView class.
 
One drawback of using these mixins is that it becomes difficult to analyze what a child class is doing and which methods to override in case of its code being too scattered between multiple classes.
Django framework offers more code-reusability than other frameworks out there.
 
As Django Project is a collection of different applications like login application, signup application.
 
These applications can be just copied from one directory to another with some tweaks to settings.py file and you won’t need to write new signup application from scratch.
 
That’s why Django is a rapid development framework and this level of code reusability is not there in other frameworks.
A Django project is a collection of web-applications that coordinate together to serve the request of the user.
 
These applications have one assigned feature and shall do only that.
 
A typical Django project consists of these four files:
 
* manage.py
* settings.py
* __init__.py
* urls.py
* wsgi.py

The last four files are inside a directory, which is at the same level of manage.py.
 
Here the structure is very logical, and the names of these files and their purpose should remain intact.
 
manage.py is the command-line utility of your Django project and this file is used to control your Django project on the server or even to begin one.
 
When Django server is started, the manage.py file searches for settings.py file, which contains information of all the applications installed in the project, middleware used, database connections and path to the main urls config.
 
The urls.py file is like a map of your whole web-project, this file examines URL and calls the right view function or transports the URL to another application-specific urls-config file.
 
This is like the main URL linker and any app installed in the settings.py which you wish to be searched by the URL should have a link here.
 
The __init__.py file is an empty file which is there to make the python interpreter understand that the directory consisting settings.py is a module/ package.
 
The wsgi.py file is for the server format WSGI, which Django supports natively. We can customize that for other server formats.
When a user enters a URL in the browser the same request is received by the Django Server.
 
The server then looks for the match of the requested URL in its URL-config and if the URL matches, it returns the corresponding view function.
 
It will then request the data from the Model of that application, if any data is required and pass it to the corresponding template which is then rendered in the browser, otherwise, a 404 error is returned.
URLs are one of the most important parts of a web application and Django provides you with an elegant way to design your own custom URLs with help of its module known as URLconf (URL Configuration). The basic functionality of this python module is to 
You can design your own URLs in Django in the way you like and then map them to the python function (View function). These URLs can be static as well as dynamic. These URLs as present in the urls.py where they are matched with the equivalent view function. 
 
Basic Syntax :
from django.urls import path
from . import views
urlpatterns = [
   path('data/2020/', views.data_2020),
   path('data/<int:year>/', views.data_year)
]
The Django Signals is a strategy to allow decoupled applications to get notified when certain events occur. Let’s say you want to invalidate a cached page everytime a given model instance is updated, but there are several places in your code base that this model can be updated. You can do that using signals, hooking some pieces of code to be executed everytime this specific model’s save method is trigged.
 
Another common use case is when you have extended the Custom Django User by using the Profile strategy through a one-to-one relationship. What we usually do is use a “signal dispatcher” to listen for the User’s post_save event to also update the Profile instance as well.
Models are a single and definitive source for information about your data. It consists of all the essential fields and behaviors of the data you have stored. Often, each model will map to a single specific database table.
 
In Django, models serve as the abstraction layer that is used for structuring and manipulating your data. Django models are a subclass of the django.db.models.Model class and the attributes in the models represent database fields.
Django’s template layer renders the information to be presented to the user in a designer-friendly format. Using templates, you can generate HTML dynamically. The HTML consists of both static as well as dynamic parts of the content. You can have any number of templates depending on the requirement of your project. It is also fine to have none of them.
 
Django has its own template system called the Django Template Language (DTL). Regardless of the backend, you can also load and render templates using Django’s standard admin.
Django web framework is managed and maintained by an independent and non-profit organization named Django Software Foundation (DSF). The primary foundation goal is to promote, support, and advance the Django Web framework.
Django-admin.py : It is a Django's command line utility for administrative tasks.
 
Manage.py : It is an automatically created file in each Django project. It is a thin wrapper around the Django-admin.py. It has the following usage:
 
* It puts your project's package on sys.path.
* It sets the DJANGO_SETTING_MODULE environment variable to points to your project's setting.py file.
A cookie is a small piece of information which is stored in the client browser. It is used to store user's data in a file permanently (or for the specified time). Cookie has its expiry date and time and removes automatically when gets expire. Django provides built-in methods to set and fetch cookie.
 
The set_cookie() method is used to set a cookie and get() method is used to get the cookie.
 
The request.COOKIES['key'] array can also be used to get cookie values.
from django.shortcuts import render  
from django.http import HttpResponse  
  
def setcookie(request):  
    response = HttpResponse("Cookie Set")  
    response.set_cookie('python-tutorial', 'example.com')  
    return response  
def getcookie(request):  
    tutorial  = request.COOKIES['python-tutorial']  
    return HttpResponse("python tutorials @: "+  tutorial);
Django uses request and response objects to pass state through the system.
When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object.
# importing HttResponse from library
from django.http import HttpResponse
 
def home(request):
    # request is handled using HttpResponse object
    return HttpResponse("Any kind of HTML Here")

 

An app is basically a Web Application that is created to do something for example, a database of employee records. A project, on the other hand, is a collection of apps of some particular website. Therefore, a single project can consist of ‘n’ number of apps and a single app can be in multiple projects.
‘Field’ is basically an abstract class that actually represents a column in the database table. The Field class, is in turn, a subclass of  RegisterLookupMixin. In Django, these fields are used to create database tables (db_type()) which are used to map Python types to the database using get_prep_value() and vice versa using from_db_value() method. Therefore, fields are fundamental pieces in different Django APIs such as models and querysets.
Sessions are fully supported in Django. Using the session framework, you can easily store and retrieve arbitrary data based on the per-site-visitors. This framework basically stores data on the server-side and takes care of sending and receiving cookies. These cookies consist of a session ID but not the actual data itself unless you explicitly use a cookie-based backend.
You may come across numerous Django Interview Questions, where you will find this question. Middleware is a framework that is light and low-level plugin system for altering Django’s input and output globally. It is basically a framework of hooks into the request/ response processing of Django. Each component in middleware has some particular task.
For example, the AuthenticationMiddleware is used to associate users with requests using sessions. Django provides many other middlewares such as cache middleware to enable site-wide cache, common middleware that performs many tasks such as forbidding access to user agents, URL rewriting, etc, GZip middleware which is used to compress the content for browsers, etc.
Django is called a loosely coupled framework because of the MTV architecture it’s based on. Django’s architecture is a variant of MVC architecture and MTV is useful because it completely separates server code from the client’s machine.
 
Django’s Models and Views are present on the client machine and only templates return to the client, which are essentially HTML, CSS code and contains the required data from the models.
 
These components are totally different from each other and therefore, front-end developers and backend developers can work simultaneously on the project as these two parts changing will have little to no effect on each other when changed.
 
Therefore, Django is called a loosely coupled framework.
A migration in Django is a Python file that contains changes we make to our models so that they can be converted into a database schema in our DBMS. So, instead of manually making changes to our database schema by writing queries in our DBMS shell, we can just make changes to our models. Then, we can use Django to generate migrations from those model changes and run those migrations to make changes to our database schema.
Django REST is a framework which lets you create RESTful APIs rapidly.
 
This framework has got funding by many big organizations and is popular because of its features over Django frameworks like Serialisation, Authentication policies and Web-browsable API.
 
RESTful APIs are perfect for web applications since they use low bandwidth and are designed such that they work well with communications over the Internet like GET, POST, PUT, etc.
When a View function returns a webpage as HttpResponse rather than a simple string, we use render().
 
Render function is a shortcut function which lets the developer to easily pass the data dictionary with the template.
 
This function then combines the template with data dictionary via templating engine.
 
Finally, this render() returns an HttpResponse with the rendered text, which is the data returned by the models.
 
Thus, Django render() bypasses lots of work for the developer and lets him use different templating engines.
 
It is because this function provides the same functionality with other templating systems.
 
The basic render Syntax :
render(request, template_name, context=None, content_type=None, status=None, using=None)
 
The request is the parameter which generates the response, the template_name containing the value where the template is stored.
 
The template name and other parameters are for passing the dictionary.
 
If you want more control, you can specify the content type, status of the data you passed and the render you are returning. That is the render().
The URLs-config in Django contains the list of urls and the mappings to view functions for those urls.
 
The urls can map to view functions, Class-based views and urls-config of another application. All these methods have their use-cases.
 
For example – If we want to keep all the URLs of our application sorted, we will use the URL-config mapping. Inside urls file, we will use view function mapping and class-based views if we require some data from the user.
Ensure that django.contrib.staticfiles is added to your INSTALLED_APPS
 
In your settings file. define STATIC_URL for ex.
 
STATIC_URL = '/static/'
 
In your Django templates, use the static template tag to create the URL for the given relative path using the configured STATICFILES_STORAGE.
{% load static %}
<img src="{% static 'my_sample/xyz.jpg' %}" alt="XYZ image"/>
Store your static files in a folder called static in your app. For example my_sample/static/my_sample/xyz.jpg
Middleware is something that executes between the request and response. In simple words, you can say it acts as a bridge between the request and response. Similarly In Django when a request is made it moves through middlewares to views and data is passed through middleware as a response.
In Django, migrations are used to propagate changes made to the models. The migrate command is basically used to apply or unapply migrations changes made to the models. This command basically synchronizes the current set of models and migrations with the database state. You can use this command with or without parameters. In case you do not specify any parameter, all apps will have all their migrations running.
Custom validation rules are the customized rules used for form validation. Suppose we have a feedback form. There are fields like messages, email, and subject. If we get message data of 1 or 2 words that are of no use to us. To check the issue, we use custom validation rules.
 
We simply define a method in our forms.py by the name clean_message().
 
This is the Django way to do it. The method’s name for custom validation should start with a clean_fieldname(). Django form system automatically looks for this type of method. Thus, these are called custom validation rules in Django.
 
It is always important to return the cleaned data of the field in a custom validation method. If not done, the method will return none instead resulting in loss of data.
Authentication and authorization are two different terms. The authentication means the verification of the entity(user) in Django’s context. Authentication will verify that the user is what they claim to be.
 
Authorization is the step after authentication. It sets the actions that can be performed by the authenticated user. Authorization is a grouping of users and allowing limited actions.
 
Both of these functionalities are achieved by django.contrib.auth application. It is a built-in application in Django.
As the name suggests this file stores the configurations or settings of our Django project, like database configuration, backend engines, middlewares, installed applications, main URL configurations, static file addresses, templating engines, main URL configurations, security keys, allowed hosts, and much more.
Both of them are of the most common types of fields used in Django. The only difference between these two is that ForeignKey field consists of on_delete option along with a model’s class because it’s used for many-to-one relationships while on the other hand, the OneToOneField, only carries out a one-to-one relationship and requires only the model’s class.
'Field' refers to an abstract class that represents a column in the database table. 
The Field class is just a subclass of RegisterLookupMixin. In Django, these fields are used to create database tables (db_types()) which are used to map Python types to the database using get_prep_value() and the other way round using from_db_value() method. Therefore, fields are fundamental pieces in different Django APIs such as models and querysets.
Permanent redirection is used only when you don’t want to lead visitors to the old URLs. The response of the permanent redirections is cached by the browser so when you try to redirect to something else it will cause issues. Since this is a browser-side operation if your user wants to move to a new page it will load the same page.
In order to view all the items from your database, you can make use of the ‘all()’ function in your interactive shell as follows:
 
* XYZ.objects.all()     where XYZ is some class that you have created in your models

To filter out some element from your database, you either use the get() method or the filter method as follows:
 
* XYZ.objects.filter(pk=1)
* XYZ.objects.get(id=1)
Django basically grew from a very practical need. World Online developers namely Adrian Holovaty and Simon Willison started using Python to develop its websites. As they went on building intensive, richly interactive sites, they began to pull out a generic Web development framework that allowed them to build Web applications more and more quickly. In summer 2005, World Online decided to open-source the resulting software, which is, Django.
NoSQL basically stands for “not only SQL”. This is considered as an alternative to the traditional RDBMS or the relational Databases.  Officially, Django does not support NoSQL databases. However, there are third-party projects, such as Django non-rel, that allow NoSQL functionality in Django. Currently, you can use MongoDB and Google App Engine.
The roles of receiver and sender in signals are:
 
Receiver : It specifies the callback function which will be connected to the signal.
Sender : It specifies a particular sender to receive a signal from.
CSRF – Cross Site Request Forgery. Csrf tokens could also be sent to a client by an attacker due to session fixation or other vulnerabilities or guessed via a brute-force attack, rendered on a malicious page that generates thousands of failed requests.
RESTful APIs are extremely beneficial for web developers to build web applications as they consume the lowest bandwidth and their design in such a way to communicate well with the internet mainly like PUT, POST, GET, etc.
Django Rest Framework (DRF) is a powerful module for building web APIs. It’s very easy to build model-backed APIs that have authentication policies and are browsable.
Django framework is too monolithic, which is true to some extent.
 
Django is MTV architecture-based framework and since Django is the controller of the architecture, it requires some rules that the developer should follow so that the framework can find and execute appropriate files at the right time.
 
Therefore, Django is one of the frameworks where file structure is as important as its architecture.
 
In Django, you get great customizability with the implementations.
 
There is just one condition that you cannot change the file names, the pre-defined lists, and variable names.
 
You can create new ones but you can’t change the predefined variables for which people say that they always have to follow a certain pattern while working on Django.
 
Django’s file structure is one of the most logical workflows.
 
The monolithic behavior is actually helping the developers to easily understand the project.
 
Even, when the company changes, the project layout remains the same.
 
Therefore, the developer would take less time to understand every aspect, will be able to perform more work productively.
Django supports many popular templating engines and by default, it comes with one very powerful templating engine.
 
Jinja Templating is a very popular templating engine for Python, the latest version in the market is Jinja 2.
 
There are some features of Jinja templating that make it a better option than the default template system in Django.
 
* Sandbox Execution : This is like a sandbox or a protected framework for automating the testing process.
* HTML Escaping : Jinja 2 provides automatic HTML Escaping, as <, >, & characters have special values in templates and if used as regular text, these symbols can lead to XSS Attacks which Jinja deals with automatically.
* Template Inheritance
* Generates HTML templates much faster than default engine
* Easier to debug, compared to default engine.
Django has its own unique qualities over Flask which is also a Python Framework. The key differences between them are :
 
* Django is a high-level Python framework while Flask is a low-level Python Framework providing you with the minimum functionality, a server would require.
* Django comes with lots of built-in functionality like Django ORM, Admin Panel, Web-templating System, Inheritance, serialization while Flask comes with a development server, NoSQL support, support for unit testing, which are already there in Django.
* Flask is more customizable than Django as Flask comes with no pre-defined structure or scaffold while Django’s file structure is fixed.
* Flask settings are user made and can be altered completely by the user. Django settings are not customizable to that degree, it has variables where only values are modifiable.
* Flask has more speed than Django when it comes to processing requests but that comes without any APIs or functionality which Django gives you in-built.
* Flask is for the developers who want more flexibility on their website and don’t need lots of built-in extra functions, while Django is for developers who want rapid development of their applications that can sustain dynamic changes to its environment.