0% found this document useful (0 votes)
30 views28 pages

Interview Questions of Django DRF

The document provides an overview of Django's architecture, specifically the Model-View-Template (MVT) design pattern, and explains the roles of each component. It also covers various features of Django including Celery for task management, static files, middleware, signals, and user authentication. Additionally, it compares Django with Flask, outlines the Django Admin utility, and discusses the Django REST framework and caching strategies.

Uploaded by

shindepankaj562
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views28 pages

Interview Questions of Django DRF

The document provides an overview of Django's architecture, specifically the Model-View-Template (MVT) design pattern, and explains the roles of each component. It also covers various features of Django including Celery for task management, static files, middleware, signals, and user authentication. Additionally, it compares Django with Flask, outlines the Django Admin utility, and discusses the Django REST framework and caching strategies.

Uploaded by

shindepankaj562
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Interview questions

1)Django Archietecture

MVT stands for Model-View-Template. Sometimes it is also referred to as MTV(Model-

Template-View). MVT is a design pattern or design architecture that Django follows to

develop web applications. It is slightly different from the commonly known MVC(Model-

View-Controller) design pattern.

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.

2. Describe the Django architecture.


Django follows the Model-View-Template(MVT) architecture based on a popular Model-
View-Controller(MVC) architectural pattern, which is followed by popular web-frameworks
like Ruby on Rails, Laravel etc.
Django’s Model-View-Template architecture divides the complete application into three
major logical components:

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.

Celery message queue

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:

 Define tasks as python functions.


 Listen to a message broker for new tasks.
 Assign the tasks to workers.
 Monitor the workers and tasks.

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

model instances and querysets.

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

2) Run manage.py collect static

3) Set up a Static Files entry on the PythonAnywhere web tab

16. What is the use of Middleware’s in Django?

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.

19. What is the usage of "Django-admin.py" and "manage.py"?

 Django-admin.py - It is a command-line utility for administrative tasks.


 manage.py - It is automatically created in each Django project and controls the
Django project on the server or even to begin one. It has the following usage:

1. Manages the project's package on the sys. path.


2. Sets the DJANGO_SETTINGS_MODULE environment variable

20. What are signals in Django?

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

Sent before or after a


Django.db.models.signals.pre_save(or)django.db.models.signals.post_save model’s save() method
calls.

Sent before or after a


model’s delete() method or
django.db.models.signals.pre_delete (or)django.db.models.signals.post_delete
query set’s delete() method
calls.

We use this signal when


django.db.models.signals.m2m_changed ManyToManyField on a
model changes.

We use this signal when


Django.core.signals.request_started(or)django.core.signals.request_finished Django starts or finishes an
HTTP request.

21. What’s the difference between a project and an app in Django?

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.

24. Explain Django session

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.

25. What are Django cookies?

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

Flask is a web microframework


Django is a web development framework for
created offering basic features of web apps. Its
Python. Its created in 2005
created in 2010

High-level Python web framework for easy and


Project Type Low-level Python web framework.
simple projects.

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.

WSGI (Web Server Gateway


Type of Framework Full-stack web framework
Interface ) framework

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.

Companies using Instagram, Coursera, Udemy. Netflix, Reddit, Lyft, MIT

Visual Debugging Django does not support visual debugging. Flask supports visual debugging.

Bootstrapping tool Builtin Not available

Working style Offers monolithic working style Offers diversified working style

The structure of the project layout for


Project layout The structure of the project layout is conventional.
the flask is random.

28. Give a brief about Django Admin.

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

Displays the usage of the information and


django-admin help
commands list provided by each application.

django-admin help
Displays available commands
–command

django-admin help Displays the command description and its


<command> available options

django-admin
Determines Django’s version
version

django-admin Depending on the changes done in the model


make migrations creates new migrations

django-admin Synchronizes the database state with the present


migrate set of models and migrations

django-admin
Starts the development server
runserver

django-admin A test mail sent to confirm Django email


sendtestemail working status

django-admin
Starts the Python interactive interpreter
shell

django-admin
Displays all the project’s migrations
showmigrations

31. How do Django views work?

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.

32. Give a brief about Django Template?

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).

33. Describe Django ORM.

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.

34. When to use iterators in 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

The most efficient and faster memory-based cache


Memcached
server

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

Database Cache data will be stored in the database and works


caching OK if you have a well-indexed database server.

36. How does Django process a request?

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:

 Django checks the root URL configuration.


 Next, Django looks at all the variable URL patterns in the URLconf for the match of
the requested URL
 If the URL matches, it returns the associated view function.
 It will then request the data from the Model of that app for any data requirement and
pass it to the corresponding Template rendered by the browser.
 Django sends an error-handling view if none of the URLs match the requested URL.

38. Explain the file structure of a typical Django project.

A typical Django project consists of these four files:

 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

40. What is the Django REST framework (DRF)?

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:

 Web browsable API


 Authentication policies
 Serialization
 Extensive documentation and excellent community support.
 Perfect for web apps since they have low bandwidth.
 Global companies like Red Hat, Mozilla, Heroku, Eventbrite, etc., trust this
framework.

41. Is Django too monolithic? Explain this statement.

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

42. Explain user authentication in Django

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.

Following are the system objects:

 users
 Groups
 Password Hashing System
 Permissions
 A pluggable backend system
 Forms Validation

Apart from this, there are various third-party web apps th


44. What is the use of forms in Django?

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.

Django's forms handle the following parts:

 Prepares and restructures data to make it ready for rendering


 Creates HTML forms for the data
 Processes submitted forms and data from the client.

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:

1. Adding a function View

In this method, import the particular View's function and add the specific URL to the URL
patterns list.

2. Adding a Class-based view

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:

46. Explain Django Security.

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:

 Cross-site scripting (XSS) protection


 SQL injection protection
 Cross-site request forgery (CSRF) protection
 Enforcing SSL/HTTPS
 Session security
 Clickjacking protection
 Host header validation

47. What is Ajax in Django?

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.

48. How to handle Ajax requests in Django?

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

49. What are Django generic views?

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

12. What happens when the Django website receives a request?


Whenever a user enters the URL in the browser, the Django server receives the request. The
server looks for the URL in its URL-config. If the server finds the match there, it will return
the corresponding view function.
Then the request is made to the model of an application to get the data. If there is any data to
be passed, pass it to the corresponding template. After, the template renders in the browser. If
the process does not work as expected, the user will get a “404” error page.

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.

14. Why is Django considered a loosely coupled framework?


Django is considered a loosely coupled framework, as it is based on the MVT architecture, a
variant of the MVC architecture. The MVT architecture is useful because it entirely separates
the server code from the client’s machine.
Models and views are available on a client machine. However, the client only receives the
template — the HTML and CSS code — along with the data from the models.
Since these components are different, the front-end and back-end developers can work
together on the same project. Making changes to a project by both the teams will not impact
each other, thus making Django a loosely coupled framework.

18. Explain ORM in Django.


ORM stands for Object-relational mapper, a special feature tool of Django. This tool helps
developers to interact with the database in a more Python-esque way. It acts as the abstraction
between the models and the database, where the main data is stored.

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.

26. What is Jinja templating?


Django comes with the support for many popular templating engines, and by default, it comes
with one very powerful templating engine, called Jinja Templating. The latest version is Jinja
2.
Below are some features of the Jinja templating, making it a better option than another
templating engine available.

 Sandbox Execution: It is a protected framework useful for automating the testing


process
 HTML Escaping: Jinja 2 comes with an automatic HTML Escaping, as <, >, &
characters that have special values in templates. If you use it as regular text, these
symbols can lead to XSS Attacks, handled by Jinja automatically.
 It shows template inheritance and generates HTML templates much faster than the
default engine
 It is easier to debug with Jina compared to the default engine

27. What is user authentication in Django?


Django has a built-in user authentication system capable of handling different objects, such as
users, groups, user-permissions, and some cookie-based user sessions.
Django’s User authentication not only helps in authenticating, but also in authorizing a user
and checking what permissions that user has.
The system operates on the following objects:

 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.

28. What is the purpose of middleware in Django?


In Django, middleware is the component that works on request and transfers it to the view,
and before it passes it to the template engine, it starts operating on a response.

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.

32. How can you set up static files in Django?


For setting up the static files in Django, you need to consider the below steps:

 Firstly, set the STATIC_ROOT in the settings.py file


 Run the manage.py collectsatic file
 Finally, set up a Static Files entry on the PythonAnywhere web tab

33. What is the session framework in Django?


Django comes with the session framework helping to store and retrieve the arbitrary data on a
per-site-visitor basis. It saves all data on the server-side and abstracts the receiving and
sending of cookies. You can implement the session via middleware.

34. How many types of inheritance styles are in Django?


Django has three inheritance styles, as mentioned below.
 Abstract base classes: You can use this style when you want a parent’s class to only
store the information you don’t want to use for each child model
 Multi-table Inheritance: You can use this style If you are subclassing an existing
model and need each model to have its database table.
 Proxy models: You can use this model if you only want to change the Python level
behavior of the model without the need to change the model’s fields

35. What are the applications of middleware in Django?


The following are some applications of middleware in Django:

 Session management
 User authentication
 Cross-site request forgery protection
 Content gzipping

36. What are signals in Django?


Signals are pieces of code that hold information regarding what is happening. You can use a
dispatcher for sending the signals and listening to those signals.
The signals become very useful when we want to do something with the data, before or after
a certain event occurs.
Here is the list of events on which we can use the Django signals:

 pre_save() trigger before save().


 post_save() trigger after save().
 pre_delete() trigger before delete().
 post_delete() trigger after delete().
 m2m_changed() triggers when there is a change in ManyToMany Field.
 request_started() trigger when the django starts the HTTP request.
 request_finished() trigger when the django finishes the HTTP request.

39. What are caching strategies in Django?


Caching implies storing the output of calculations to avoid performing the same calculations
repetitively. Django comes with a robust cache system helping to create dynamic pages.
Therefore, it eliminates the need to evaluate pages repeatedly for every request. The
following table highlights some of the significant caching strategies:

Strategy Description

Memcached It is a memory-based cache server.

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.

Database caching The database stores the cache data.

41. How is the “migrate” command used in Django?


In Django, migrations are used for propagating the changes made to models. You can use the
migrate command to apply and remove the migration changes made to models.
This command helps synchronize the current set of models and migrations with the database
state. You can also use this command with or without passing the parameters. If you do not
specify any parameters, all apps will have all their migrations running.
Command:

python manage.py migrate

Output
Migrating the project for the first time will show a similar result.

42. What is the response cycle in Django?


Whenever a user requests a web page, Django will create an HttpRequest object containing
the important metadata about that request. After that, Django will load a particular view,
passing the HttpRequest as its first argument to the view function. Each view then returns an
HttpResponse object.
The following are the steps that take place when a request is received by Django:

 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.

1.How dictonary is uniq from other one, main purpose of dictonary in


python django ?.
ans:- Dictionaries are used to store data values in key:value pairs. A
dictionary is a collection which is ordered*, changeable and do not
allow duplicates. As of Python version 3.7, dictionaries are ordered.
In Python 3.6 and earlier, dictionaries are unordered.

2.differance between RDBMS(Relational Database Management Systems) and


NoSql(non-SQL database)
ans:-1.RDBMS : RDBMS stands for Relational Database Management Systems.
It is most popular database. In it, data is store in the form of row
that is in the form of tuple. It contain numbers of table and data can
be easily accessed because data is store in the table. This Model was
proposed by E.F. Codd.
2.NoSql : NoSQL Database stands for a non-SQL database. NoSQL
database doesn’t use table to store the data like relational database.
It is used for storing and fetching the data in database and generally
used to store the large amount of data. It supports query language and
provides better performance.

3.how to use django caching?


ans:-Type of django cache's
1.Database Caching
2.File-System Caching
3.Local-Memory Caching
4.Dummy Caching
5.Custom Cache System

4.Does Django work with MongoDB,Basic Info about It?


ans:- - Djongo makes zero changes to the existing Django ORM
framework, which means unnecessary bugs and security vulnerabilities do
not crop up.
-It simply translates a SQL query string into a MongoDB query
document. As a result, all Django features, models, etc., work as is.

5.what is redis ,how its working?


ans:- Django uses django-redis to execute commands in Redis. Looking at
our example app in a text editor, we can see the Redis configuration in
the settings.py file. We define a default cache with the CACHES
setting, using a built-in django-redis cache as our backend.

Redis allows us to store data in multiple high-level data structures


including strings, hashes, lists, sets, and sorted sets. This gives us
more flexibility on the type and amount of information we can store on
a Redis data store.

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.

7.Basic Info About Flask?


ans:- Flask is a micro web framework written in Python. It is
classified as a microframework because it does not require particular
tools or libraries. It has no database abstraction layer, form
validation, or any other components where pre-existing third-party
libraries provide common functions.

8.what is rest framework overview in django?


ans:- REST is a loosely defined protocol for listing, creating,
changing, and deleting data on your server over HTTP. The Django REST
framework (DRF) is a toolkit built on top of the Django web framework
that reduces the amount of code you need to write to create REST
interfaces.

9.what is middleware in django?


ans:- Middleware is a framework of hooks into Django's request/response
processing. It's a light, low-level “plugin” system for globally
altering Django's input or output. Each middleware component is
responsible for doing some specific function.

10.what is mixins in django rest framework?


ans:- The mixin classes provide the actions that are used to provide
the basic view behavior. Note that the mixin classes provide action
methods rather than defining the handler methods, such as . get() and .
post() , directly. This allows for more flexible composition of
behavior.

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.

12.Types of Sql join?


ans:- 1.Cross join. A cross join returns all possible combinations of
rows of two tables (also called a Cartesian product).
2.Join/inner join. An inner join, also known as a simple join,
returns rows from joined tables that have matching rows.
3.Left outer join/left join.
4.Right outer join/right join.
5.Full outer join.

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

It contains the Django project configuration.


The setting.py is the most important file, and it is used for adding all the applications and
middleware applications. This is the main setting file of the Django project.
This contains several variable names, and if you change the value, your application will work
accordingly.
It contains sqlite3 as the default database. We can change this database to Mysql,
PostgreSQL, or MongoDB according to the web application we create.
It contains some pre-installed apps and middleware that are there to provide basic
functionality.

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.

What’s the difference between a project and an app?

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.

Whats is include in url.py

The include() function allows referencing other URLconfs. Whenever Django


encounters include(), it chops off whatever part of the URL matched up to that
point and sends the remaining string to the included URLconf for further processing.

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

Starts from Vowel -> even


Not vowel -> odd place

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

ID FirstName LastName Age


1 Daniel Smith 25
2 Mike Smith 22
3 Jenny Richards 28
4 Robert Black 22
5 Noah Fritz 30
6 Ashley Johnson 25

SELECT LastName,SUM(Age) as SumAge FROM maintable_X7N7J where LastName


LIKE "Smith";

# weekdays = {10: 'sun', 12: 'mon', 6: 'fri', 7: 'sun', 9: 'mon', 8: 'mon', 3: 'tue', 4: 'wed', 5: 'thu'}

# days = {}

# for k,v in weekdays.items():


# # print(v)
# if v not in days.values():
# days[k] = v
# else:
# print(k,v)
# # days[k] = v
# print(days)

list_input = [12.5, 15, 20, "New Delhi", "India", 34, "Axtria"]

# 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)

O/P = ['even', 'odd', 'even', 'string', 'string', 'even', 'string']

1.D/b list and Dit


2. D/B dot PYC file and Dot PY file.
3. Have u used slice-in in python explain.
4. How u describe ur working style.
5. Coding test: For coding try recursion and for loop method
We have a staircase with N number of steps
We are allowed to take 1 or 2 steps.
The number of steps to be written..
What are the different ways to climb the steps???
6. Do you have experience of working for lot of database oriented project?

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()

Print from 1 to 100 without loops and numbers in Python


zero = int(False)
one = int(True)
hundred = int(f"{one}{zero}{zero}")

# def shownum(i):
# if i <= hundred:
# print(i)
# shownum(i + one)

# shownum(one)

for i in range(one, hundred+one):


print(i)

# Given a number n, return true if it is a power of ten. Otherwise, return false.


# # A number n is a power of ten, if there exists an integer x such that n == 10^x
# print(is_power_of_ten(1)) # true
# print(is_power_of_ten(10)) # true
# print(is_power_of_ten(1000)) # true
# print(is_power_of_ten(5)) # false
# print(is_power_of_ten(20)) # false
# print(is_power_of_ten(-1)) # false
# print(is_power_of_ten(0.00001)) # true
import math
def is_power_of_ten(n):
if (n == pow(10, (math.log(n) / math.log(10)))):
return True
else:
return False

# Function to check if x is power of 5


def isPowerOfFour(n):
if (n == pow(10, (math.log(n)/math.log(10)))):
return True
return False

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')

sum of all elements of all the subsets in power set

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)

# Driver program to test printPowerSet


set = [1,2,3];
printPowerSet(set, 3);

Find number of consucative vowels in given string

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))

You might also like