Interview Questions of Django DRF
Interview Questions of Django DRF
1)Django Archietecture
develop web applications. It is slightly different from the commonly known MVC(Model-
MVT determines the total structure and workflow of a Django application. In an MVT
architecture —
The Model manages the data and is represented by a database. A model is basically a
database table.
The View receives HTTP requests and sends HTTP responses. A view interacts with a
model and template to complete a response.
The Template is basically the front-end layer and the dynamic HTML component of a
Django application.
1. Model
2. View
3. Template
All these three components are responsible for handling the different aspects of the web
application.
Model: The models handle the database schema for the web applications. It maintains and
represents the complete application data into the database. The default relational database
used by the model is SQLite which is generally used in development, but in production we
can use the MySQL and Postgres.
View: The view component manages all the logic of the application that we want to render on
the user’s browser. In Django, the view acts as a bridge between the models and the
templates. In the views, we can fetch the data from the models and render it on the template.
Template: The template component is the collection of static parts of the application such as
the HTML, CSS, JavaScript, and Image files. The view uses the template as the base on
which the data should be presented, because at the end, the web-application uses the static
files to represent the content on the user browser.
2)what is celery
Celery is a distributed task queue that can collect, record, schedule, and perform tasks outside
of your main program.To receive tasks from your program and send results to a back end,
Celery requires a message broker for communication. Redis and RabbitMQ are two message
brokers that developers often use together with Celery.
Celery is a task queue/job queue based on distributed message passing. It is focused on real-
time operation, but supports scheduling as well. The execution units, called tasks, are
executed concurrently on a single or more worker servers.
A queue is a data structure that works based on the first-in, first-out principle. We assign
work to the workers through a message queue. The worker processes the tasks in the order in
which the message broker queued them.
The queue ensures that each worker processes a single task at a time, and only a single
worker processes a particular task.
Celery
Celery makes it easier to implement the task queues for many workers in a Django
application.
Functions of Celery:
What is Redis?
Redis is an in-memory data structure store that can be used as a caching engine. Since it
keeps data in RAM, Redis can deliver it very quickly.
Serializers
Serializers allow complex data such as querysets and model instances to be converted to
native Python datatypes that can then be easily rendered into JSON , XML or other content
types. Serializers also provide deserialization, allowing parsed data to be converted back into
complex types, after first validating the incoming data
ModelSerializer class which provides a useful shortcut for creating serializers that deal with
Is Django a CMS?
No, Django is not CMS (Content Management System). It's just a web framework and
programming tool that allows you to build websites.
15. What are static files in Django? And how can you set them?
In Django, static files are the files that serve the purpose of additional purposes such as
images, CSS, or JavaScript files. Static files managed by “django.contrib.staticfiles”. There
are three main things to do to set up static files in Django:
1) Set STATIC_ROOT in settings.py
Middlewares in Django is a lightweight plugin that processes during request and response
execution. It performs functions like security, CSRF protection, session, authentication, etc.
Django supports various built-in middlewares.
Django includes a "signal dispatcher" to notify decoupled applications when some action
takes place in the framework. In a nutshell, signals allow specific senders to inform a suite of
receivers that some action has occurred. They are instrumental when we use more pieces of
code in the same events.
Django provides a set of built-in signals that enable users to get notified of specific actions.
Signal Description
The app is a module that deals with the dedicated requirements in a project. On the other
hand, the project covers an entire app. In Django terms, a project can contain different apps,
while an app features in various projects.
Django uses the session to keep track of the state between the site and a particular browser.
Django supports anonymous sessions. The session framework stores and retrieves data on a
per-site-visitor basis. It stores the information on the server side and supports sending and
receiving cookies. Cookies store the data of session ID but not the actual data itself.
A cookie is a piece of information stored in the client's browser. To set and fetch cookies,
Django provides built-in methods. We use the set_cookie() method for setting a cookie and
the get() method for getting the cookie. You can also use the request.COOKIES['key'] array
to get cookie values.
26. Flask vs. Django: What's the difference between Flask & Django?
Flask and Django are the two most popular Python web frameworks. The following table lists
some significant differences between Django and Flask
26. Flask vs. Django: What's the difference between Flask & Django?
Flask and Django are the two most popular Python web frameworks. The following table lists
some significant differences between Django and Flask
Comparison Factor Django Flask
The best features of Django are open-source, rapid The best features of Flask are open
Features development, robust documentation, great source, lightweight, and require less
community, and easy to learn. code to develop an app.
Templates, Admin,
Built-in Requires installation
and ORM
Django Web Framework supports a large number Flask Web Framework doesn't offer
Flexibility
of third-party applications. support for third-party applications.
Visual Debugging Django does not support visual debugging. Flask supports visual debugging.
Working style Offers monolithic working style Offers diversified working style
Django Admin is the command-line utility for administrative tasks. It's a preloaded interface
to fulfill all web developer's needs and is imported from the "django.contrib packages".
Django Admin interface has its user authentication and offers advanced features like
authorizing the access, CMS (Content Management System), managing various models, etc.
You can even perform the following tasks using Django admin as listed out in the table:
Command Task
django-admin help
Displays available commands
–command
django-admin
Determines Django’s version
version
django-admin
Starts the development server
runserver
django-admin
Starts the Python interactive interpreter
shell
django-admin
Displays all the project’s migrations
showmigrations
Django views are the critical component of the framework They serve the purpose of
encapsulation. They encapsulate the logic liable to process a user's request and return a
response to the user.
Either they return HTTP responses or raise an exception such as 404 in Django. Besides,
Views also perform tasks like reading records from a database, generating PDF files, etc.
Every app in Django comes with a views.py file, and this contains the views functions. Views
function can be imported directly in the URLs file in Django.
To achieve that, you have to import the view function in the urls.py file first and add the
path/URL that the browser should request to call that View function.
Django Templates generate dynamic web pages. Using templates, you can show the static
data and the data from various databases connected to the app through a context dictionary.
You can create any number of templates based on project requirements. Even it's OK to have
none of them.
Django template engine handles the templating in the Django web framework. Some template
syntaxes declare variables, filters, control logic, and comments.
Django ships built-in backends for its template system called the Django template language
(DTL).
In Django, the most notable feature is Object-Relational Mapper (ORM), which allows you to
interact with app data from various relational databases such as SQLite, MySQL, and
PostgreSQL.
Django ORM is the abstraction between web application data structure (models) and the
database where the data is stored. Without writing any code, you can retrieve, delete, save,
and perform other operations over the database.
The main advantage of ORMs is rapid development. ORMs make projects more portable. It's
easier to change the database with Django ORM.
Iterators are containers in Python containing several elements. Every object in the iterator
implements two methods that are __init__() and the __next__() methods.
In Django, the fair use of an iterator is when you process results that take up a large amount
of memory space. For this, you can use the iterator () method, which evaluates the QuerySet
and returns the corresponding iterator over the results.
35. What is Django caching? And explain the strategies used to implement it.
Caching is the process of saving expensive calculation output to avoid performing the same
calculation again.
Django supports a robust cache system to save web pages such that they don't have to be
evaluated repeatedly for each request.
They are few strategies to implement caching in Django, and the following table lists them:
Strategy Description
Filesystem
Cache files store in serial order in separate files.
caching
Local-
If you have not specified any other, this is the default
memory
cache. It’s per-process and threads safe as well.
caching
Whenever the Django Server receives a request, the system follows an algorithm to determine
which Python code needs execution. Here are the steps that sum up the algorithm:
manage.py
settings.py
__init__.py
urls.py
wsgi.py
The final four files are inside a directory, which is at the same level as manage.py.
manage.py is the command-line utility of your Django project and controls the
Django project on the server.
settings.py file includes information on all the apps installed in the project.
The urls.py file acts as a map for the whole web project.
The __init__.py file is an empty file that makes the python interpreter understand that
the directory consisting of settings.py is a module/ package.
The wsgi.py file is for the server format WSGI
Django REST framework is a flexible and powerful toolkit for building Web APIs rapidly.
The following are the significant reasons that are making REST framework perfect choice:
The Django framework is monolithic, which is valid to some extent. As Django's architecture
is MVT-based, it requires some rules that developers need to follow to execute the
appropriate files at the right time.
With Django, you get significant customizations with implementations. Through this, you
cannot change file names, variable names, and predefined lists.
Django's file structure is a logical workflow. Thus the monolithic behavior of Django helps
developers to understand the project efficient
Django comes with a built-in user authentication system to handle objects such as users,
groups, permissions, etc. It not only performs authentication but authorization as well.
users
Groups
Password Hashing System
Permissions
A pluggable backend system
Forms Validation
Forms serve the purpose of receiving user inputs and using that data for logical operations on
databases. Django supports form class to create HTML forms. It defines a form and how it
works and appears.
45. Can you explain how to add View functions to the urls.py file?
There are two ways to add the view function to the main URLs config:
In this method, import the particular View's function and add the specific URL to the URL
patterns list.
This one is a more class-based approach. For this, import the class from the views.py and
then add the URL to the URL patterns. An inbuilt method is needed to call the class as a
view.
Write the name of the function on the previous method as shown below:
Protecting user's data is an essential part of any website design. Django implements various
sufficient protections against several common threats. The following are Django's security
features:
AJAX (Asynchronous JavaScript And XML) allows web pages to update asynchronously to
and from the server by exchanging data in Django. That means without reloading a complete
webpage you can update parts of the web page.
It involves a combination of a browser built-in XMLHttpRequest object, HTML DOM, and
JavaScript.
To handle Ajax requests in the Django web framework, perform the following:
Initialize Project
Create models
Create views
Write URLs
Carry out requests with Jquery Ajax.
Register models to admin
Writing views is a heavy task. Django offers an easy way to set Views called Generic Views.
They are classes but not functions and stored in "django.views.generic".
Generic views act as a shortcut for common usage patterns. They take some common idioms
and patterns in view development and abstract them to write common views of data without
repeating yourself quickly
13. Can you customize Django’s admin interface? If yes, then how?
Yes, you can customize Django’s admin interface. Django’s admin is another entirely
customizable application. It enables you to download another third-party application for a
different view. You can create your own admin application to have complete control over it.
Also, for customizing the Django admin site, you can change the settings of the admin site
object.
Also, you can make the desired changes to your models and then apply them in the Django
admin for adding specific applications, such as the search bar. You can customize even a
smaller detail of your Django admin interface. Still, it is advisable to create a new admin
rather than making so many changes at a lower level.
Using ORM, you can retrieve, save, and delete the data from a database without the need to
write any SQL code for it. This tool will help eliminate many loopholes since it lets you
maintain control over your code, and is developed in Python.
It does not matter whether the Database is a SQLite, MySQL, Postgre or Oracle the ORM
makes sure that the developer writes the same code for all databases.
Django uses the ORM known as Django ORM, it uses classes inherited from models.Modle,
to create tables under any database.
Users
Permissions
Groups
Password Hashing System
Forms Validation
A pluggable backend system
Third-party web applications can be used instead of the default system as you have much
more control over user authentication and many other features.
The above image displays the list of middleware installed by default within your Django
framework.
It serves several purposes, including session management and user authentication.
Session management
User authentication
Cross-site request forgery protection
Content gzipping
Strategy Description
This caching strategy helps in caching the values stored as separate files in a serialize
Filesystem caching
order.
Local-memory It is the default cache, and it is used if you have not specified any other. It is a per-
caching process and thread-safe cache.
Output
Migrating the project for the first time will show a similar result.
Firstly, the settings.py file, which contains various middleware classes, is loaded
All the middleware classes get executed in the same order in which they are
mentioned
Now, the request will be moved to the URL Router. The URL Router gets the URL
path from the request and later tries to map with the given URL paths within the
urls.py.
After mapping, it calls the equivalent view function, from where the corresponding
response is generated.
The response now passes through the response middleware and is sent back to the
client/browser
19. What is the difference between a session and a cookie? A cookie is a bit of data stored by
the browser and sent to the server with every request. Cookies are used to identify sessions. A
session is a collection of data stored on the server and associated with a given user (usually
via a cookie containing an id code). The main difference between a session and a cookie is
that session data is stored on the server, whereas cookies store data in the visitor’s browser.
Sessions are more secure than cookies as it is stored in the server. A cookie can be turned off
from the browser. Data stored in cookies can be stored for months or years, depending on the
life span of the cookie. But the data in the session is lost when the web browser is closed.
6.When A request Goes between Two DataBase How Can You Reduce The
Response Time?
ans:- 1.Using Redis Caching it will be Redus the Response time
2.Caching ensures fast delivery to visitors. Without caching, a
browser requests assets from the server each time a page loads
instead of accessing them from a local or intermediary cache.
11.sql oveview ?
ans:- SQL is a query language designed to query and extract data from
databases. A database is nothing more than a set of related
information. A telephone directory, for example, is a database of
names, phone numbers, and addresses of all people living in a specific
region. Database management systems have been around for years. With
today’s technology, the accepted use of database management systems
have began to flow in other directions, driven by the growing demand of
businesses, increased volumes of corporate data, and Internet
technologies. SQL is a standard language used to communicate with a
relational database.
Manage.py
This file is used as a command-line utility for our projects. We will use this file
for debugging, deploying, and running our web applications.
The file contains the code for running the server, makemigrations or migrations, and several
other commands as well, which we perform in the code editor.
It performs the same things as django-admin but also provides some project-
specific functionality.
wsgi.py
The Web Server Gateway Interface (WSGI, pronounced whiskey or WIZ-ghee) is a simple
calling convention for web servers to forward requests to web applicat0ions or frameworks
written in the Python programming language.
. wsgi.py
When you will complete your journey from development to production, the next task is
hosting your application. Here you will not be using the Django web server, but the WSGI
server will take care of it
WSGI stands for Web Server Gateway Interface, it describes the way how servers interact
with the applications.
It is a very easy task, you just have to import middleware according to the server you want to
use. For every server, there is Django middleware available that solves all the integration and
connectivity issues.
asgi.py
ASGI works similar to WSGI but comes with some additional functionality. ASGI stands
for Asynchronous Server Gateway Interface. It is now replacing its predecessor WSGI.
Init.py
This is an empty file as you can see below in the image. The function of this file is to tell the
Python interpreter that this directory is a package and involvement of this __init.py_ file in it
makes it a python project
settings.py
3. urls.py
URL is a universal resource locator, it contains all the endpoints that we should have for our
website. It is used to provide you the address of the resources (images, webpages, websites,
etc) that are present out there on the internet.
In simpler words, this file tells Django that if a user comes with this URL, direct them to that
particular website or image whatsoever it is.
2. admin.py
Admin.py file is used for registering the Django models into the Django administration.
It is used to display the Django model in the Django admin panel. It performs three major
tasks:
a. Registering models
b. Creating a Superuser
c. Logging in and using the web application
We will learn more about the admin panel in the next article about Admin Interface.
3. apps.py
Apps.py is a file that is used to help the user include the application configuration for their
app.
Users can configure the attributes of their application using the apps.py file.
However, configuring the attributes is a rare task a user ever performs, because most of the
time the default configuration is sufficient enough to work with.
4. models.py
Models.py represents the models of web applications in the form of classes. It is considered
the most important aspect of the App file structure.
Models define the structure of the database. It tells about the actual design, relationships
between the data sets, and their attribute constraints.
5. views.py
Views are also an important part when we talk about the Django app structure. Views provide
an interface through which a user interacts with a Django web application. It contains all the
views in the form of classes.
We use the concept of Serializers in Django Rest_Framework for making different types of
views. Some of these are CustomFilter Views, Class-Based List Views, and Detail Views.
6. urls.py
Urls.py works the same as that of the urls.py in the project file structure. The primary aim
being, linking the user’s URL request to the corresponding pages it is pointing to.
You won’t find this under the app files. We create this by clicking on the New file option
written on the top, after the Project name.
7. tests.py
Tests.py allows the user to write test code for their web applications. It is used to test the
working of the app.
Its working is quite complex. We will discuss it in more detail in the upcoming articles.
An app is a web application that does something – e.g., a blog system, a database of
public records or a small poll app. A project is a collection of configuration and apps
for a particular website. A project can contain multiple apps. An app can be in
multiple projects.
The idea behind include() is to make it easy to plug-and-play URLs. Since polls are
in their own URLconf (polls/urls.py), they can be placed under “/polls/”, or under
“/fun_polls/”, or under “/content/polls/”, or any other path root, and the app will still
work.
makemigrations,
By running makemigrations, you’re telling Django that you’ve made some changes
to your models (in this case, you’ve made new ones) and that you’d like the changes
to be stored as a migration.
Migrations are how Django stores changes to your models (and thus your database
schema) - they’re files on disk. You can read the migration for your new model if you
like; it’s the file polls/migrations/0001_initial.py. Don’t worry, you’re not
expected to read them every time Django makes one, but they’re designed to be
human-editable in case you want to manually tweak how Django changes things.
Migrate
Practical questions
Delhi
Mumbai
Australia
Bhopal
Amsterdam
Paris
UK
USA
India
Aus
Delhi
Amsterdam
Mumbai
UK
BHopal
USa
Paris
India
—--------------------
Input: 1234500
Output: Twelve lakh thirty four thousand five hundred
def search(**kwargs):
kwargs = {k: v for k, v in kwargs.items() if v}
queryset = Organization.objects.filter(**kwargs)
return queryset
In this MySQL challenge, your query should return LastName and the sum of Age from your
table for all users with a LastName = Smith. The column title of the summed ages should be
SumAge. Your output should look like the following table.
LastName Sumage
smite 47
# weekdays = {10: 'sun', 12: 'mon', 6: 'fri', 7: 'sun', 9: 'mon', 8: 'mon', 3: 'tue', 4: 'wed', 5: 'thu'}
# days = {}
# result = [("even" if i%2==0 else ("odd" if i%2 != 0 else "string")) for i in list_input]
# result = ["even" if isinstance(i, int) and int(i) % 2 == 0 else ("odd" if isinstance(i, int) and
int(i) % 2==1 else "string") for i in list_input ]
result = ["even" if isinstance(i, int) and int(i) % 2 == 0 else ("odd" if isinstance(i, int) and
int(i) % 2==1 else "string") for i in list_input ]
print(result)
read only
doesn't have remove method
it uses round parantheses ex.(1,2,3)
the *args rep
dictonary
find len of a tuple
it is ordered
class Tup:
def __init__(self,*args):
self.nos = (args)
# self.no1 = args[0]
# self.no2 = args[1]
# self.no3 = args[2]
# def set_val(self):
# self.nos[1] = 5class Editor:
def __init__(self, n):
self.n = n
self.data = []
self.ud = []
self.rd = []
def add(self):
for i in range(self.n):
self.ud.append(i)
def undo(self):
last = self.rd[-1]
self.rd.pop()
self.ud.append(last)
return self.ud
def redo(self):
last = self.ud[-1]
self.ud.pop()
self.rd.append(last)
return self.rd
def print_data(self):
print(self.ud)
ed = Editor(5)
ed.add()
ed.print_data()
# ed.undo()
# print(ed.data)
# ed.print_data()
ed.redo()
ed.print_data()
def print_no(self):
print(self.nos)
def tup_len(self):
cnt = 0
for i in self.nos:
cnt += 1
return cnt
class Tup2:
# t = Tup(1,2,3)
t = Tup({"no1":1, "no2":2,"no3":3,}, 0, 1, 4, 5)
print(t.tup_len())
# t.print_no()
class Editor:
def __init__(self, n):
self.n = n
self.data = []
self.ud = []
self.rd = []
def add(self):
for i in range(self.n):
self.ud.append(i)
def undo(self):
last = self.rd[-1]
self.rd.pop()
self.ud.append(last)
return self.ud
def redo(self):
last = self.ud[-1]
self.ud.pop()
self.rd.append(last)
return self.rd
def print_data(self):
print(self.ud)
ed = Editor(5)
ed.add()
ed.print_data()
# ed.undo()
# print(ed.data)
# ed.print_data()
ed.redo()
ed.print_data()
# def shownum(i):
# if i <= hundred:
# print(i)
# shownum(i + one)
# shownum(one)
test_no = 1000
# print(isPowerOfFour(test_no))
# print(isPowerOfFour(1)) # true
# print(isPowerOfFour(10)) # true
# print(isPowerOfFour(1000)) # true
# print(isPowerOfFour(5)) # false
# print(isPowerOfFour(20)) # false
# print(isPowerOfFour(-1)) # false
# print(isPowerOfFour(0.00001)) # true
if(isPowerOfFour(test_no)):
print(test_no, ' is a power of 10')
else:
print(test_no, ' is not a power of 10')
import math;
def printPowerSet(set,set_size):
pow_set_size = (int) (math.pow(2, set_size));
counter = 0;
j = 0;
sum = 0
for counter in range(0, pow_set_size):
for j in range(0, set_size):
if((counter & (1 << j)) > 0):
sum += set[j]
print(sum)
def isVowel(c):
return (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u')
def countVowel(s):
cnt, res = 0,0
for i in range(len(s)):
if isVowel(s[i].lower()):
cnt += 1
else:
res = max(res, cnt)
cnt = 0
return max(res, cnt)
s = "AAABCA"
print(countVowel(s))