Top Django Interview Questions - Solved

Django is a web development framework built on python. It is highly advanced and robust framework used for developing web apps and is being used by various tech companies. This page will explore scenario based django interview questions on concepts and its architecture. We encourage you to understand these concepts and logics and do a hands-on before going for an interview.

Q: What is a Model-View-Template (MVT) pattern and how it is implemented in Django.

Model-View-Template or MVT is a a design pattern in django and it explains how the datastructure, urls and views interact or communicates within django. The pattern has three main components:

Model: This represents the datastructure or how data data will be stored. It is analogus to database tables . It is responsible for storing and manipulating data along with implementation of any business logic or rules.

Template: These are HTML or web templates that is required to be shown on UI. Analogus to presentation layer. It is responsible for defining the layout and structure of the user interface, and it also renders the data ,provides by models, on the UI .

View: This acts as the controller of the django web apps . All backend calculations are generally done here. It is responsible for handling user input, interacting with the django model to retrieve and manipulate data, and render the required templates to the api.

Models are defined in Python classes that are derived from Django's models "Model class".
These are like a DB table where you store data in the form of records. You can create different models and each model will have some fields. for example if you create a model to store user's expense data then you can have an expense model where fileds be like : "groceries", "investments", "savings" etc.

These will then be added to database with the help of django migrations. Default DB available is SQLlite.

Below is an example of contact table where you can store contact information of users:

Q: What could be the issue if you do not find model in django admin panel?

Django models must be migrated as well as registered in admin.py file inside the django app folder which user has created.

Within the file, you need to import the admin and the models you want to register as below :

Q: How do you pass django variable from view to templates?

when you create a variable in view.py file where you havefunction for a template and inside that function you have python varible which holds some value after some calculation in python.

Below is the example of django view.py file where created parameter is paased to template:


In above example we have two variables, var1 and var2. in var1, we are loading all the objects of table "mymodel" and in var2 , we are putting a fixed string value i.e. "statute".

Within HTML template, var2 can be directly called within double curly braces with name "variable2" as this is the name we are passing to template using render

and variable1 can be called within for loop inside HTML template.

Q: How would you select only top three content from your blog or model within django template?

Within for loop to loop over the contents of a table or django model, we can use for loop counter as below to selsect only top or bottom records.
In the below example, we are selecting only top 3 content of a django model.

Q: How does Django handle form submission and validation?

This can be done in two ways. Either you can directly use HTML/CSS form or you can use djnago form utility.

When you use html form, you create all the form fields within template and with post method you can pass the form value back to django view function.

When you use django form utility, you need to create "forms.py" within your app. In this file, one can create different forms usings form class and then can create fields within those classes.
Django form utility provides better usage and arrangement of forms. An illustration is shown below:



This django form need to be called within views.py file at respective function.

We need to use the {% form %}template tag and specify the form to be rendered at our web page.

When we submit form, Django validates the data and dispaly error if there is any invalid data or process the data and redirects user to a new page if the data is valid. We can do this validation also within our views.py file to customize as per our needs

Q: What is a Django migration and how do you use them?

Whenever you create a model in models.py file or make changes to existing model like modifying fields, adding or deleting table, you need to migrate those additions and updates to migration file.
Migrations are necessary for django to understand the latest structure of you models.

Django mogration is a two step process:



Step1: Make Migrations


python manage.py makemigrations

The above step will make migration file having information about the changes to the models.

Step2: Migrate Migrations


python manage.py migrate


The above step apply changes to your database.

In case you don't have any changes and you execute the make migration command, then it will show you that "no changes detected"

Q: How does Django handle static files (e.g. CSS, JavaScript) and templates?

In Django, static files such as CSS, JavaScript, and images are usually stored in static folder or directory within django app. This directory is typically located at /path/to/project/appname/static.

One need to configure static files URL and directory path in the "settings.py" file within django like below.



For example, to include a CSS file in a template, you could use the following code:



As static url is already configured in "urls.py" file, django will find the static directory withing base directory and will search for directories and files as mentioned in the link.

Q: What are the default files and folders created when you create a django project?

Whenever we create a django project with command "django-admin startproject testproj1" below files and folders are created by default inside project folder:
1.) One folder again with same project name
2.) manage.py python file



within project folder, below files are created :


Q: How to filter items or values from database in django ?

Selecting and filtering out object can be done in below ways :

A) : Selecting All Records :
model.objects.all()
it will select all record with all fields.

B) : Selecting Particular Records :
myuser.objects.get(first_name='john')
It will select records where first name is 'john'

C) : Selecting Particular Records and field :
myuser.objects.get(first_name='john').last_name
It will select all records with firstname as 'john' and give their 'last_name' value only not other fields of the record.

Q: How to give permissions to user in django ?

User can be given permissions like admin, auth or account permissions by superuser from django admin panel.

Within django admin panel, you need to go to users, then select the particular user then within permission sections one can ad permission.



One can give user a staff status also.



Q: How do you set up and use a Django test suite?

In Django, you can use the TestCase class provided by Django's TestCase module to create a test suite for your Django app.
To set up a test suite in Django, you will need to create a tests.py file in your app directory and define a series of test functions or test classes that inherit from TestCase.

For example, to create a simple test that checks if a certain condition is true, you could define a test function like this:


from django.test import TestCase
def test_something(self):
self.assertTrue(1 + 1 == 2)

To run your tests, you can use the test management command:


python manage.py test

This will run all of the tests in your Django app and display the results.

You can also specify the name of a specific app or test to run only those tests. For example:


python manage.py test myapp
python manage.py test myapp.tests.test_something

To set up a more complex test suite with multiple test cases and test functions, you can define a test class that inherits from TestCase and define a series of test methods within it.

For example:


from django.test import TestCase

class MyTestCase(TestCase):
def test_something(self):
self.assertTrue(1 + 1 == 2)

def test_something_else(self):
self.assertEqual('a', 'a')

Each test method should test a specific aspect of your code and assert that the expected output is produced. You can use the various assertion methods provided by TestCase, such as assertTrue, assertEqual, and assertRaises, to test the output of your code.

It's important to note that when running tests in Django, the test database is used instead of the production database. This ensures that your tests are isolated and do not affect your production data.

Overall, setting up and using a Django test suite allows you to write and run automated tests for your Django app to ensure that it is working as expected and to catch and fix any issues before deploying your app.

Q: How do you handle user authentication and authorization in Django?

In Django, user authentication and authorization are provided by the built-in auth application. This application includes a number of views, forms, and models that you can use to handle user authentication and authorization in your Django project.

To use the auth application in your Django project, you will need to include it in the INSTALLED_APPS list in your Django settings and include the auth URLs in your urls.py file.

For example, in your settings file you might have:


INSTALLED_APPS = [
# ...
'django.contrib.auth',
# ...
]

And in your urls.py file:


from django.contrib import auth

urlpatterns = [
# ...
path('accounts/', include('django.contrib.auth.urls')),
# ...
]

This will include the auth application in your Django project and set up the necessary URLs for handling user authentication and authorization.

To handle user authentication, the auth application includes a number of views and forms that you can use. The most common ones are the login and logout views, which allow users to log in and log out of your application.

To use these views, you can include the login and logout URLs in your urls.py file and create the corresponding templates for the login and logout views.

For example, in your urls.py file:


urlpatterns = [
# ...
path('accounts/login/', auth.views.login, name='login'),
path('accounts/logout/', auth.views.logout, name='logout'),
# ...
]

And in your templates directory, you might have a login.html template for the login view and a logout.html template for the logout view.

To handle user authorization, the auth application includes a number of decorators and utility functions that you can use to restrict access to certain views or templates based on a user's permissions.

For example, you can use the @login_required decorator to require that a user be logged in to access a particular view or template:


from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
# view code here

This will ensure that only logged-in users can access the my_view view.

You can also use the user_passes_test decorator to require that a user have certain permissions to access a view or template. For example:

from django.contrib.auth.decorators import user_passes_test


def my_permission_check(user):
return user.is_superuser

@user_passes_test(my_permission_check)
def my_view(request):
# view code here

This will ensure that only users with the is_superuser flag set to True can access the my_view view.

Overall, Django's auth application provides a comprehensive set

Q: How do you implement internationalization (i18n) in a Django project?

In Django, internationalization (i18n) refers to the process of adapting a Django application for use in multiple languages. Django provides a number of tools and features to make it easy to internationalize your application.

To enable i18n in a Django project, you will need to set the USE_I18N setting to True in your Django settings file and include the django.middleware.locale.LocaleMiddleware middleware in your MIDDLEWARE list.

For example, in your settings file you might have:


USE_I18N = True
MIDDLEWARE = [
# ...
'django.middleware.locale.LocaleMiddleware',
# ...
]

You will also need to include the django.middleware.locale.LocaleMiddleware middleware in your MIDDLEWARE list.

To translate text in a Django template, you can use the trans {% trans %} template tag. This tag allows you to mark text as translatable and specify a translation for each language.
For example, to translate the text "Hello, world!" into multiple languages, you could use the following code in your template:


{% trans "Hello, world!" %}

To provide translations for this text, you will need to create a translation file for each language that you want to support. These files are typically stored in a locale directory within your Django app and use the .po file format.

To create a translation file, you can use the makemessages management command:


python manage.py makemessages -l de

This will create a translation file for the German language (de) in the locale directory. You can then edit this file to provide translations for the text in your templates.
To activate a translation for a particular language, you can use the activate management command:


python manage.py activate de

This will set the active language to German and use the translations in the de translation file for the text in your templates.

You can also set the active language based on the user's language preference by including the django.middleware.locale.LocaleMiddleware middleware in your MIDDLEWARE list and setting the LANGUAGE_CODE setting in your Django settings file.

For example, in your settings file you might have:


LANGUAGE_CODE = 'en-us'

This will set the default language to English (US). The LocaleMiddleware middleware will then attempt to determine the user's preferred language based on the Accept-Language HTTP header and activate the appropriate translation.

Overall, Django's i18n features make it easy to internationalize your application and provide translations for the text in your templates. By using the {% trans %} template tag and translation files, you can ensure that your application is fully localized and accessible to users in multiple languages.

Q: How do you optimize a Django application for performance?.

There are a number of ways you can optimize a Django application for performance. Some of the most common techniques include:

Use a high-performance database: Django supports a number of different databases, and choosing the right one for your application can significantly impact performance. Some popular databases for Django include PostgreSQL and MySQL.

Use caching: Caching can help reduce the number of database queries and the amount of processing required by your application, resulting in improved performance. Django provides a number of caching options, including in-memory caching, file-based caching, and cache-backed sessions.

Use a fast web server: Choosing a fast web server such as Nginx or Apache can help improve the performance of your Django application.

Use a fast WSGI server: Django uses a WSGI server to serve web requests. Choosing a fast WSGI server such as Gunicorn or uWSGI can help improve the performance of your Django application.

Use efficient database queries: Optimizing your database queries can help reduce the amount of time and resources required to execute them, resulting in improved performance. This may involve using indexing, using the right database engine, and avoiding unnecessary queries.

Use efficient templates: Optimizing your Django templates can help reduce the amount of processing required to render them, resulting in improved performance. This may involve using template inheritance and limiting the number of template tags and filters used.

Use a production-ready server configuration: Running Django in a production environment requires a different server configuration than running it in a development environment. Using a production-ready server configuration can help improve the performance of your Django application.

Overall, optimizing a Django application for performance involves identifying and addressing bottlenecks in your application's performance and implementing best practices for Django development. By following these techniques, you can improve the performance of your Django application and provide a better user experience for your users.

Q: How do you deploy a Django application to a production server?

Deploying a Django application to a production server involves a number of steps, including setting up a production-ready server environment, configuring the Django application for production use, and transferring the application files to the server.

Here is a general outline of the steps you might take to deploy a Django application to a production server:

Set up a production-ready server environment: This may involve installing a web server such as Nginx or Apache, a WSGI server such as Gunicorn or uWSGI, and any other dependencies required by your Django application.

Configure your Django application for production use: This may involve setting the DEBUG setting to False in your Django settings file, configuring static file handling, and setting up a production-ready database such as PostgreSQL or MySQL.

Transfer the application files to the server: You will need to transfer the code and any static files for your Django application to the server. This can be done using a version control system such as Git, or by manually transferring the files via FTP or SFTP.

Set up a virtual environment and install dependencies: You should create a virtual environment on the server and install the required Python packages for your Django application. This can be done using the pip package manager.

Collect static files: If you are using static files in your Django application (e.g. CSS, JavaScript, images), you will need to run the collectstatic management command to collect these files and place them in a static files directory on the server.

Configure the web server: You will need to configure the web server to serve your Django application. This may involve creating a virtual host configuration for your application and pointing the web server to the correct location for the application files and static files.

Restart the web server: After making changes to the web server configuration, you will need to restart the web server to apply the changes.

Overall, deploying a Django application to a production server involves setting up a production-ready server environment, configuring the Django application for production use, and transferring the application files to the server. By following these steps, you can successfully deploy your Django application to a production server.

Q: What is a Django QuerySet and how do you use it to retrieve data from the database?

In Django, a QuerySet is a collection of objects from a Django model. It represents a group of database records, and you can use it to retrieve, filter, and manipulate data from the database.

A QuerySet is created by calling the objects.all() method on a Django model. This will return a QuerySet containing all the objects in the database for that model.

For example, if you have a model called Person with a few records in the database, you could retrieve all of the records using a QuerySet like this:


from myapp.models import Person

people = Person.objects.all()

This will create a QuerySet containing all of the Person objects in the database.

You can also use various methods and filters on a QuerySet to retrieve a specific subset of objects. For example, you can use the filter() method to filter the QuerySet based on certain criteria:


people = Person.objects.filter(first_name='John')

This will create a QuerySet containing only the Person objects with a first_name of 'John'.

You can also chain multiple filters together to create more complex queries:


people = Person.objects.filter(first_name='John').filter(last_name='Doe')

This will create a QuerySet containing only the Person objects with a first_name of 'John' and a last_name of 'Doe'.

You can also use the exclude() method to exclude certain objects from the QuerySet:


people = Person.objects.exclude(first_name='John')

This will create a QuerySet containing all Person objects except those with a first_name of 'John'.

To retrieve a single object from the database, you can use the get() method on a QuerySet. This will return the first object that matches the specified criteria, or raise an exception if no objects match.

For example:


person = Person.objects.get(pk=1)

This will retrieve the Person object with a primary key (pk) of 1 from the database.

Overall, Django QuerySets allow you to efficiently retrieve, filter, and manipulate data from your Django models and the underlying database. You can use them to build complex queries and retrieve the specific data you need for your application.