Django interview questions and answers 👇
Explain the use of session framework in Django?↑
In Django, the session framework enables you to store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the receiving and sending of cookies. Session can be implemented through a piece of middleware.
List out the inheritance styles in Django?↑
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
What is Django?↑
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.
How do you connect your Django project to the database?↑
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)
What are Models?↑
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.
What are views?↑
Django views serve the purpose of encapsulation. They encapsulate the logic liable for processing a user’s request and for returning the response back to the user. Views in Django either return an HttpResponse or raise an exception such as Http404. HttpResponse contains the objects that consist of the content that is to be rendered to the user. Views can also be used to perform tasks such as read records from the database, delegate to the templates, generate a PDF file, etc.
What are templates?↑
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.
What is the difference between a Project and an App?↑
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.
What is mixin?↑
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.
When can you use iterators in Django ORM?↑
Iterators in Python are basically containers that consist of a countable number of elements. Any object that is an iterator implements two methods which are, the init() and the next() methods. When you are making use of iterators in Django, the best situation to do it is when you have to process results that will require a large amount of memory space. To do this, you can make use of the iterator() method which basically evaluates a QuerySet and returns the corresponding iterator over the results.
What are the signals in Django?↑
Signals are pieces of code which contain information about what is happening. A dispatcher is used to sending the signals and listen for those signals.
What is the role of Cookie in Django?↑
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.
Django is an MVC based framework, how does this framework implement MVC?↑
Django is based on MTV architecture which is a variant of MVC architecture. MVC is an acronym for Model, View, and Controller. There are different parts of a website so that they can develop and execute in different machines to achieve faster and more responsive websites. Django implements MTV architecture by having 3 different components and they are all handled by Django itself.
Models are the part which is models.py file in a Django application, which defines the data structure of the particular application.
View are the mediators between models and templates, they receive the data from the Model and make it a dictionary and return the same as a response to a request to the Template.
The Template is the component with which user interacts, and it generates both statically and dynamically in the Django server.
That’s how the Django implements 3 components and work in coordination with each other.
How is Django’s code reusability feature different from other frameworks?↑
Django framework offers more code-reusability then 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.
What happens when a typical Django website gets a request?↑
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.
Why is Django called loosely coupled framework?↑
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.
Explain the importance of settings.py file and what data/ settings it contains.↑
When Django server starts, it first looks for settings.py. As the name settings, it is the main settings file of your web application. Everything inside your Django project like databases, backend engines, middlewares, installed applications, main URL configurations, static file addresses, templating engines, allowed hosts and servers and security key stores in this file as a list or dictionary.
So, when your Django server starts it executes settings.py file and then loads particular engines and databases so that when a request is given it can serve the same quickly.
Why does Django use regular expressions to define URLs? Is it necessary to use them?↑
Django uses a very powerful format for storing URLs, that is regular expressions. RegEx or regular expression is the format for sophisticated string searching algorithms. It makes the searching process faster. Although it’s not necessary to use RegEx when defining URLs.
They can be defined as normal string also, Django server should still be able to match them, but when you need to pass some data from the user via URL, then RegEx is used. The RegEx also makes much cleaner URLs then other formats.
Django is too monolithic. Explain this statement.↑
Django framework is too monolithic, that 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 customisability 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 pre-defined 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.
Why permanent redirecting is not a good option?↑
Permanent redirecting is not good an option because the browser caches the response generated by the permanent redirect. This is the difference between permanent and temporary redirect. It causes all sorts of issues when you change that redirect to something different.
Since the browser has cached the redirect before, this time it won’t look on the server for the changed redirection and will load the previously saved redirect. So, even though the developer might have redirected the user to a different page, it will still load the same page. It is browser/ client-side operation, therefore, the user can’t even do anything about the same.
Because of this reason, permanent redirecting is not a good option as informing the users to clear their internal caching data is not good for any website.
Explain user authentication in Django?↑
Django comes with a built-in user authentication system, which handles objects like users, groups, user-permissions and some cookie-based user sessions. Django’s User authentication not only authenticates (verifying the user identity) the user but also authorizes him (determines what permissions user have).
The system consists and operates on these objects:
- Password Hashing System
- Forms Validation
- A pluggable backend system
There are many third-party web applications which we can use in place of the default system as they provide much more control over user authentication with more features.
Explain context variable lookups in Django.↑
Context variables are variables passed in templates. The DTL (Django Templating Language) replaces these variables. A context dictionary is used to perform the replacement. We pass the context dictionary alongside the render() alongside template information.
DTL has its own way of filling these variables and it’s in order. The template system can handle complex Python data structures as variables. The context variable lookups come in the role when the data is a dictionary, class object, etc.
The context lookup will fill the value in this order.
- Dictionary Values: The template system will look for dictionaries matching the variable name. It matches the key name with the name after the dot(.) operator.
- Class Object Attribute values: If it didn’t find any dictionaries it will look for a class object. First lookups are done for attributes.
- Class Object Methods: It looks for a particular attribute of that name. If the attribute is not found then it looks for methods.
- List-Index lookup: At last, it will look for any lists with corresponding names. If it didn’t find any lists then it considers variable as an Invalid Variable.
What are custom validation rules in form data?↑
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.
What is the difference between authentication and authorization?↑
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.
What is Pagination?↑
Pagination is a concept where we separate or divide data into different pages. It’s divided into multiple pages. The pages are provided as per user-request.
In the context of web applications: Suppose you search for anything on Google. Though Google claims they have found thousands of results in the resulting page, they give you only 10-20 results. Then you press the next page and you get more results. That is pagination.
Showing user only limited data is good for both of them. The user can sort the results easily and smoothly reach the information he/she wants. The bandwidth cost is not much for some results. Since the transfer-data is small, it gives results on low network speeds.
Pagination is also good for the server. The server can simply store the data in queryset or database and wait for the client to request more. This reduces the template overhead which would have been to generate a response. Generating a response with 1000 data is much more expensive than 10-20 data.
Pagination can drastically improve performance if done the right way.
Explain the use of migrate command in Django?↑
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.
What are the roles of receiver and sender in signals?↑
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.
What is CSRF?↑
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.
What is CRUD?↑
The most common task in web application development is to write create, read, update and delete functionality (CRUD) for each table. It refers to the set of common operations that are used in web applications to interact with data from the database. It provides a CRUD interface that allows users to create, read, update or delete data in the application database.
Django helps us with its simplified implementation for CRUD operations using Function-Based views and class-based views:
Function- based views are simple to implement and easy to read but they are hard to customize or extend the functionality. Code reuse is not allowed and so there is repetitiveness.
Class-based views - In no time CRUD operations can be implemented using CBVs. As the model evolves changes would be reflected automatically in CBVs. CBVs are easily extendable and allow code reuse. Django has built-in generic CBVs which makes it easy to use.
Can you tell us something about the Django admin interface?↑
Django is actually of preloaded interface designed to fulfill the requirement of web developers. Basically, it indicates any requirements for the web developer to make other admin because the whole process is time-consuming and costly. Django admin interface supports user authentication and follows most of the included features. The application Django admin is imported from the Django.contrib package. This imported application is also expected to get control by the corresponding organization hence it does not require an additional front end.
The Django admin interface provides a number of advanced features like-
Managing multiple models
Content management system
How is the reusability feature of Django different from the rest of the frameworks?↑
Django offers maximum code reusability to the developers as compared to other frameworks. This framework is also a collection of various applications including login application or signup application. With the help of this framework, a large number of applications can directly be copied from one directory to the next following some of the settings.py files. With this framework, developers can easily work over the application without writing the new sign up application. This is the reason which supports the rapid development framework in Django and there are no other compatible frameworks supporting this level of code reusability.
How does Django's admin interface support customization?↑
Django admin interface easily supports the customization and developer can download various other third-party applications and install them in a completely different view. Also, if the developer wants overall control over their admin then they can make their own admin application. The admin site can also be customized for example changing the properties of admin.site.object. this admin interface also supports the changes in modifications in models and to apply them in Django admin for specific applications. The Django admin interface supports customization exact from the lowest level and the developer can also create new admin interfaces.
How are RESTful APIs beneficial for developers?↑
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.
What is the use of the include function in the urls.py file in Django?↑
As in Django there can be many apps, each app may have some URLs that it responds to. Rather than registering all URLs for all apps in a single urls.py file, each app maintains its own urls.py file, and in the project’s urls.py file we use each individual urls.py file of each app by using the include function.
Explain how you can use file based sessions?↑
To use file based session you have to set the SESSION_ENGINE settings to “django.contrib.sessions.backends.file”
What is the typical usage of middlewares in Django?↑
Some usage of middlewares in Django is:
- Session management
- Use authentication
- Cross-site request forgery protection
- Content Gzipping
What is DRF of Django Rest Frame work?↑
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.
What is token based authentication system?↑
A token based authentication system is a security system that authenticates the users who attempt to log in to a server, a network, or some other secure system, using a security token provided by the server
How to implement social login authentication in Django?↑
Run the development server to make sure all is in order. The install python-social-auth using the pip install command. Update settings.py to include/register the library in the project Update the database by making migrations.
Update the Project’s urlpatterns in urls.py to include the main auth URLs. Create a new app https://apps.twitter.com/app/new and make sure to use the callback url http://127.0.0.1:8000/complete/twitter. In the project directory, add a config.py file and grab the consumer key and consumer secret and add them to the config file.
Finally add urls to the config file to specify the login and redirect urls. Do a sanity check and add friendly views.
Mention the differences between Django, Pyramid and Flask.↑
- Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.
- Pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.
- Django can also used for larger applications just like Pyramid. It includes an ORM.
Explain the use of decorators.↑
Decorators in Python are used to modify or inject code in functions or classes. Using decorators, you can wrap a class or function method call so that a piece of code can be executed before or after the execution of the original code. Decorators can be used to check for permissions, modify or track the arguments passed to a method, logging the calls to a specific method, etc.
Django Advanced Interview Questions
How would you compare Node.js and Django?↑
It heavily depends on the priorities you set in your project. The most common criteria are: database type (e.g. Django for a relational one), security (Django offers great security), rapid development (also Django). Other criteria may include: better performance (Node.js is more fitting), creating features from the ground up (also Node.js) or better client-side processing (Node.js).
A distinctive caveat of Node.js lies in its asynchronous elements: they require the developer to be ever so vigilant because code errors may not reveal themselves until late in production.
How can we use model inheritance?↑
Django’s object-oriented models can be easily mapped to database table structures, creating inheritance properties that they will be sharing. That way, the inheriting model will not interfere with the base one. It is common for a web project to include multiple models; to showcase inheritance, we can use a base model (which we can name “content” and have it store general description values related to it: title, description, dates of creation and/or modification, etc.) together with another model (that we can name “audio”). The “audio” model will inherit the properties of the base model “content”, while also utilizing its own: source, link, embed code.
Having created the base model, we let Django map it to a table named content — and makes it inherit from model.Model. We then create the “audio” model but make it inherit from “content” instead of model.Model. The convenience of this method comes from the fact that Django manages the inheritance systems autonomously, creating two tables: content and audio respectively. This relation can also be accessed via SQL methods.
How can we optimize a Django project’s performance?↑
Although it depends on the databases and models used in the project, there are some methods that always prove to be effective:
- Analyzing the runtime of functions via the line__profiler_ module. Sometimes we may notice that the code runs slowly — and we need to examine our functions line-by-line. Using the IPython debugger with the line_profiler module, we can see exactly how much time each function takes to execute — and then we optimize the code, if needed.
- SQL logging. To dissect a function suspected of low performance even further, we can utilize SQL logging, getting a list of every SQL query that gets executed. It is important to limit this type of logging to a single function — otherwise, the printout would simply flood us with information.
What is Unicode, what is UTF-8 and how do they relate?↑
Unicode is an international encoding standard that works with different languages and scripts. It consists of letters, digits or symbols representing characters from across the world. UTF-8 is a type of encoding, a way of storing the code points of Unicode in a byte form, so you can send Unicode strings over the network or store them in files.
How would you scale an existing application when starting a new project?↑
I see performance and scaling as two separate things. Performance is how fast a user is served and scaling refers to the number of users that can be served by an app at the same time. Usually, time is best spent developing during the early stages of a project. When scale does become an issue, usually business is good and there are sufficient funds to optimize the application.
Are there situations where you wouldn’t use Python/Django?↑
Sure. For example, if a project involves some kind of reasoning it might be better to use Prolog and have Python interface with it. Of course, I would be mindful about adding more complexity to the stack by introducing a new language.