Here we have mentioned most frequently asked django Interview Questions and Answers specially for freshers and experienced.


 

1. Explain what is Django?

Ans:

Django is a web framework in python to develop a web application in python.

2. Mention what are the features available in Django?

Ans:

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

3. Mention the architecture of Django architecture?

Ans:

Django architecture consists of
Models: It describes your database schema and your data structure
Views: 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: The Django framework and URL parsing

4. Why Django should be used for web-development?

Ans:

  • It allows you to divide code modules into logical groups to make it flexible to change
  • To ease the website administration, it provides auto-generated web admin
  • It provides pre-packaged API for common user tasks
  • It gives you template system to define HTML template for your web page to avoid code duplication
  • It enables you to define what URL be for a given function
  • It enables you to separate business logic from the HTML
  • Everything is in python

5. Explain how you can create a project in Django?

Ans:

To start a project in Django, you use command $ django-admin.py and then use the command
Project
_init_.py
manage.py
settings.py
urls.py

6. Explain how you can set up the Database in Django?

Ans:

You can use the command edit mysite/setting.py , it is a normal python module with module level representing Django settings.
Django uses SQLite by default; it is easy for Django users as such it won’t require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default’ item to match your database connection settings
Engines: you can change database by using ‘django.db.backends.sqlite3’ , ‘django.db.backeneds.mysql’, ‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.oracle’ and so on
Name: The name of your database. In the case if you are using SQLite as your database, in that case database will be a file on your computer, Name should be a full absolute path, including file name of that file.
If you are not choosing SQLite as your database then setting like Password, Host, User, etc. must be added.

7. Give an example how you can write a VIEW in Django?

Ans:

Views are Django functions that take a request and return a response. To write a view in Django we take a simple example of “Guru99_home” which uses the template Guru99_home.html and uses the date-time module to tell us what the time is whenever the page is refreshed. The file we required to edit is called view.py, and it will be inside mysite/myapp/
Copy the below code into it and save the file
from datatime import datetime
from django.shortcuts import render
def home (request):
return render(request, ‘Guru99_home.html’, {‘right_now’: datetime.utcnow()})
Once you have determined the VIEW, you can uncomment this line in urls.py
# url ( r ‘^$’ , ‘mysite.myapp.views.home’ , name ‘Guru99’),
The last step will reload your web app so that the changes are noticed by the web server.

8. Explain how you can setup static files in Django?

Ans:

There are three main things required to set up static files in Django

  • Set STATIC_ROOT in settings.py
  • run manage.py collectsatic
  • set up a Static Files entry on the PythonAnywhere web tab

9. Mention what does the Django templates consists of?

Ans:

The template is a simple text file. It can create any text-based format like XML, CSV, HTML, etc. A template contains variables that get replaced with values when the template is evaluated and tags (% tag %) that controls the logic of the template.

10. Explain the use of session framework in Django?

Ans:

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.



 

11. Explain how you can use file based sessions?

Ans:

To use file based session you have to set the SESSION_ENGINE settings to “django.contrib.sessions.backends.file”

12. Explain the migration in Django and how you can do in SQL?

Ans:

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.
django-admin.py sqlsequencreset
Use this command to generate SQL that will fix cases where a sequence is out sync with its automatically incremented field data.

13. Mention what command line can be used to load data into Django?

Ans:

To load data into Django you have to use the command line Django-admin.py loaddata. The command line will searches the data and loads the contents of the named fixtures into the database.

14. Explain what does django-admin.py makemessages command is used for?

Ans:

This command line executes over the entire source tree of the current directory and abstracts all the strings marked for translation. It makes a message file in the locale directory.

15. List out the inheritance styles in Django?

Ans:

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

16. Mention what does the Django field class types?

Ans:

Field class types determines
The database column type
The default HTML widget to avail while rendering a form field
The minimal validation requirements used in Django admin and in automatically generated forms

17. Mention the differences between Django, Pyramid and Flask.

Ans:

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.

18. Discuss the Django architecture.

Ans:

Django MVT Pattern:

Django Architecture

The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user.

19. Explain how you can set up the Database in Django.

Ans:

You can use the command edit mysite/setting.py , it is a normal python module with module level representing Django settings.
Django uses SQLite by default; it is easy for Django users as such it won’t require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default’ item to match your database connection settings.
Engines: you can change database by using ‘django.db.backends.sqlite3’ , ‘django.db.backeneds.mysql’, ‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.oracle’ and so on
Name: The name of your database. In the case if you are using SQLite as your database, in that case database will be a file on your computer, Name should be a full absolute path, including file name of that file.
If you are not choosing SQLite as your database then settings like Password, Host, User, etc. must be added.
Django uses SQLite as default database, it stores data as a single file in the filesystem. If you do have a database server—PostgreSQL, MySQL, Oracle, MSSQL—and want to use it rather than SQLite, then use your database’s administration tools to create a new database for your Django project. Either way, with your (empty) database in place, all that remains is to tell Django how to use it. This is where your project’s settings.py file comes in.
We will add the following lines of code to the setting.py file:

DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.sqlite3',
'NAME' : os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

20. Give an example how you can write a VIEW in Django?

Ans:

This is how we can use write a view in Django:

from django.http import HttpResponse
import datetime

def Current_datetime(request):
now = datetime.datetime.now()
html = “It is now %s” % now
return HttpResponse(html)
Returns the current date and time, as an HTML document




 

21. Mention what the Django templates consists of.

Ans:

The template is a simple text file. It can create any text-based format like XML, CSV, HTML, etc. A template contains variables that get replaced with values when the template is evaluated and tags (% tag %) that controls the logic of the template.

22. Explain the use of session in Django framework?

Ans:

Django provides session that lets you store and retrieve data on a per-site-visitor basis. Django abstracts the process of sending and receiving cookies, by placing a session ID cookie on the client side, and storing all the related data on the server side.
So the data itself is not stored client side. This is nice from a security perspective.

23. List out the inheritance styles in Django.

Ans:

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.

24. How To Save An Image Locally Using Python Whose URL Address I Already Know?

Ans:

We will use the following code to save an image locally from an URL address

import urllib.request
urllib.request.urlretrieve("URL", "local-filename.jpg")

25. How can you Get the Google cache age of any URL or web page?

Ans:

Use the following URL format:
http://webcache.googleusercontent.com/search?q=cache:URLGOESHERE
Be sure to replace “URLGOESHERE” with the proper web address of the page or site whose cache you want to retrieve and see the time.

26. You are required to scrap data from IMDb top 250 movies page. It should only have fields movie name, year, and rating.

Ans:

We will use the following lines of code:

from bs4 import BeautifulSoup
import requests
import sys
url = 'http://www.imdb.com/chart/top'
response = requests.get(url)
soup = BeautifulSoup(response.text)
tr = soup.findChildren("tr")
tr = iter(tr)
next(tr)
for movie in tr:
title = movie.find('td', {'class': 'titleColumn'} ).find('a').contents[0]
year = movie.find('td', {'class': 'titleColumn'} ).find('span', {'class': 'secondaryInfo'}).contents[0]
rating = movie.find('td', {'class': 'ratingColumn imdbRating'} ).find('strong').contents[0]
row = title + ' - ' + year + ' ' + ' ' + rating
print(row)

The above code will help scrap data from IMDb’s top 250 list

27. What is map function in Python?

Ans:

map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given. #Follow the link to know more similar functions.

28. How to get indices of N maximum values in a NumPy array?

Ans:

We can get the indices of N maximum values in a NumPy array using the below code:

import numpy as np
arr = np.array([1, 3, 2, 4, 5])
print(arr.argsort()[-3:][::-1])

Output
[ 4 3 1 ]

29. How do you calculate percentiles with Python/ NumPy?

Ans:

We can calculate percentiles with the following code

import numpy as np
a = np.array([1,2,3,4,5])
p = np.percentile(a, 50) #Returns 50th percentile, e.g. median
print(p)

Output
3

30. What advantages do NumPy arrays offer over (nested) Python lists?

Ans:

Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python’s list comprehensions make them easy to construct and manipulate.
They have certain limitations: they don’t support “vectorized” operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element.
NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.
NumPy array is faster and You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc.


 

31. Explain the use of decorators.

Ans:

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.

32. What is the difference between NumPy and SciPy?

Ans:

In an ideal world, NumPy would contain nothing but the array data type and the most basic operations: indexing, sorting, reshaping, basic elementwise functions, et cetera.
All numerical code would reside in SciPy. However, one of NumPy’s important goals is compatibility, so NumPy tries to retain all features supported by either of its predecessors.
Thus NumPy contains some linear algebra functions, even though these more properly belong in SciPy. In any case, SciPy contains more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms.
If you are doing scientific computing with python, you should probably install both NumPy and SciPy. Most new features belong in SciPy rather than NumPy.

33. How do you make 3D plots/visualizations using NumPy/SciPy?

Ans:

Like 2D plotting, 3D graphics is beyond the scope of NumPy and SciPy, but just as in the 2D case, packages exist that integrate with NumPy. Matplotlib provides basic 3D plotting in the mplot3d subpackage, whereas Mayavi provides a wide range of high-quality 3D visualization features, utilizing the powerful VTK engine.