
Domains
Agile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
SAFe 6.0 Scrum Master (SSM) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
SAFe 6.0 Release Train Engineer (RTE) CertificationScaled Agile, Inc.
16 Hours
Trending
SAFe® 6.0 Product Owner/Product Manager (POPM)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterTech Courses and Bootcamps
Full Stack Developer BootcampAccreditation Bodies
Scrum AllianceTop Resources
Scrum TutorialProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationSkills
Change ManagementMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramUniversity Programs
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CourseRoles
Project ManagerAccreditation Bodies
PMITop Resources
Theories of MotivationCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationMicrosoft
32 Hours
Azure Solution Architect CertificationMicrosoft
40 Hours
Azure DevOps CertificationAWS
24 Hours
Systems Operations on AWS Certification TrainingAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramBootcamps
Career Kickstarter
100 Hours
Trending
Cloud Engineer BootcampRoles
Cloud EngineerOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAuthorized Partners of
AWSTop Resources
Scrum TutorialIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All DevOps Coursesicon-git-commitCertifications
Axelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
16 Hours
ITIL Practitioner CertificationPeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamTop Resources
ITIL Practice TestData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataBootcamps
Job Oriented
6 Months
Trending
Data Science BootcampJob Oriented
289 Hours
Data Engineer BootcampJob Oriented
6 Months
Data Analyst BootcampJob Oriented
288 Hours
New
AI Engineer BootcampSkills
Data Science with PythonRoles
Data ScientistOn-Demand Courses
Data Analysis Using ExcelTop Resources
Machine Learning TutorialDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesRoles
DevOps EngineerOn-Demand Courses
CI/CD with Jenkins XGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationTIBCO
36 Hours
TIBCO Spotfire TrainingCertification
30 Hours
Data Visualization with QlikView CertificationCertification
16 Hours
Sisense BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingTop Resources
Python Data Viz LibsCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v12) CertificationISACA
22 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) Certification16 Hours
Certified Information Privacy Professional - Europe (CIPP-E) CertificationISACA
16 Hours
COBIT5 Foundation16 Hours
Payment Card Industry Security Standards (PCI-DSS) CertificationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeBootcamps
Career Kickstarter
6 Months
Best Seller
Full-Stack Developer BootcampJob Oriented
3 Months
Best Seller
UI/UX Design BootcampEnterprise Recommended
6 Months
Java Full Stack Developer BootcampCareer Kickstarter
490+ Hours
Front-End Development BootcampCareer Accelerator
4 Months
Backend Development Bootcamp (Node JS)Skills
ReactOn-Demand Courses
Angular TrainingTop Resources
Top HTML ProjectsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer Certification5+ Hours
Blockchain 101 CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptTop Resources
Python TutorialWeb Development
4.8 Rating 39 Questions 30 mins read7 Readers

Django follows MVC pattern (Model-View-Controller), also referred to as MTV (Model-Template-View).
Expect to come across this popular question in Django interview questions.
When a user requests a page, Django determines whether the request URL pattern is mentioned in URLs.py. Once the regex matches, Django calls the corresponding view. HttpRequest is passed as an argument to that view function, and the implementation part is executed further.
CSRF – Cross Site Request Forgery. Csrf tokens could also be sent to a client by an attacker due to session fixation or other vulnerabilities or guessed via a brute-force attack, rendered on a malicious page that generates thousands of failed requests.
Django is a high-level Python-based, open-source web framework written in Python to develop a web application to encourage rapid development and clean, pragmatic design. Django follows the model-view-template architectural pattern and developed by a fast-moving online-new operation. Django is designed to handle intensive deadlines of a newsroom and the stringent requirements of the experienced web developers who developed it. It allows you to build a high performing web application quickly.
Django, a web application framework is a collection of modules that are grouped together to enable you to create an application or a website from an existing source. This collection of modules makes the development of web application or a website fast and easier.
A single person can design and still can include advanced functionality like authentication support, admin panel, management panel, contact forms, comment boxes, file upload, and many more. To create a website from scratch you would have to develop these components by yourself. These components are already built and you just need to configure them as per your requirement to build your site. You can focus on developing your app as Django offers a big collection of modules that can be easily used in projects and takes care of most of the hassle of web development.
Django is named after one of the best guitarists of all time Django Reinhardt, a gypsy jazz guitarist from the 1930s to early 1950s.
2.2.1 is the latest and stable version now.
MVT that is Model, View, Template, and MVC that is Model View, Controller, are design patterns. Programmers may use, extend or not use these ready to use design patterns.
MVC design pattern was built specifically to separate out business logic and data. MVC allows representing the same data in multiple ways. In MVC pattern Model is the “data” part, View is the “presentation” part and the Controller is the “coordination” part.
MVT is Model View Template. Here View acts as “Controller” and has no one to one mapping in case of Django. The major difference between the two patterns is that Django takes care of the Controller part. The Django template is an HTML file mixed with Django Template Language. The developer develops the Model, the view and the template then maps it to a URL and then Django does the magic to serve it to the user.
A staple in Django technical interview questions, be prepared to answer this one.
Below are the supported and tested versions of Django-MySQL’s requirements:
Before setting connection below prerequisite is taken into consideration-
1. MySQL is installed
2. MySQL-python package is installed (python interface to MySQL)
3. Django configured
Now let us see the steps to connect to MySQL -
1. Open settings.py from the directory of the Django project.
2. Update the default key in the DATABASE dictionary. Set ENGINE, NAME, USER and PASSWORD you choose when installing MySQL.
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'djangoApp',
'USER':'root',
'PASSWORD':'mysql',
'HOST':'localhost',
'PORT':'3306'
},
}3. Open a command window and activate a virtual environment and change it to the Django project directory.
4. Type python maanage.py syncdb and create the underlying tables required for the Django project.
If there is no error, your connection between Python, Django, and MySQL is successful.
Static files may include CSS, JavaScript, and images. Django refers to these images, JavaScript, or CSS files as static files. Django provides django.contrib.staticfiles to manage static files.
You may want to serve these static files alongside your site.
STATIC_url = '/static/'
{% load static %}
<img src = "{% static "my_app/example.jpg" %}" alt ="My image"/>
Django supports anonymous sessions. The Session framework allows you to store and retrieve arbitrary data on per site visitor basis. Django stores data on server-side and retrieves it by sending and receiving cookies. These cookies contain session IDs.
Enabling sessions -
Using a piece of middleware, sessions are implemented.
To enable session -
Open and update the MIDDLEWARE setting as below.
'django.contrib.sessions.middleware.SessionMiddleware'
Default settings.py has SessionMiddleware activated.
You can remove SessionMiddleware line from MIDDLEWARE_CLASSES and 'django.contrib.sessions' from your INSTALLED_APPS if you don't want to use sessions.
Configuring session engine
Django store sessions in the database by default. Django can be configured to store session data in two ways.
1. Using database-backed sessions - You need to add 'django.contrib.sessions' to INSTALLED_APPS settings if you want to use database-backed sessions.
Run manage.py syncdb to install a single database table to store session data.
2. Using cached sessions - For better performance, cache-based session backend can be used. To store session data you need to configure the cache. You can store data in two ways -
Django middleware is a framework of hooks to modify request and response objects.
If you want to modify the HttpRequest object which is sent to the view, or you want to modify the HttpResponse object returned from the view, you can use middleware.
Django provides some default middleware like AuthenticationMiddleware.
Middleware is used in a number of key pieces of functionality in the Django project and you can use CSRF middlewares to prevent cross-site request forgery attacks or to handle session data. With the use of middleware Authentication and authorization can be accomplished. To shape the flow of data through the application, you can write your own middleware classes.
One of the following methods must have in Django middleware.
process_request, process_response, process_view and process_exception.
These methods will be collected by WSGI Handler and called in the listed order.
Before any view executes, Django wants user attribute to be sent on request and to accomplish this Django takes a middleware approach. So AuthenticationMiddleware can modify the request object like -
https://github.com/django/django/blob/master/django/contrib/auth/middleware.py#L22
The same way to show the user's timezone on the page of the user, you can access the user's timezone in all views. You can use TimezoneMiddleware.
TimezoneMiddleware is dependent on request.user and request.user is populated in AuthenticationMiddleware. So timezone middleware written must come after AuthenticationMiddleware in the tuple settings.MIDDLEWARE_CLASSES.
It's no surprise that this one pops up often in Django interview questions for experienced person.
In Django, a model is a special kind of object and it is saved in the database. In the model, you will store information about users, your books, etc. In terms of the database, you can think of a spreadsheet with columns (fields), and rows (data), as a model.
We are assuming here that the project is created and database connection is set up, and you are in a project folder( or directory where manage.py file is).
To create an application 'dailyblog' execute the command -
$ python manage.py startapp dailyblog
The new dailyblog directory will be created with the number of files.
Register your dailyblog with the Django project. Open settings.py in the code editor and Update INSTALLED_APPS tuple by adding a line containing 'dailyblog'.
//settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dailyblog', ]
In the dailyblog/models.py file, we will define models, that is an object. Here we will define our blog post.
Now open dailyblog/models.py in the code editor, remove all from it and write below code -
//models.py from django.conf import settings from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title
Let us see what the above model code means -
Lines starting with 'from' or 'import' add some bits from other files.
In Django, migration is a way of applying changes made in models that are adding the field, deleting model, etc. into a database. To manage database schema changes migrations are a great way. You will find Django has created migration files inside the migration folder for each model. Each table is mapped to the model. Most migrations are designed to be automatic, but you need to know when to migrate, and when to run migrations.
Django has various commands to interact with migrations and Django's handling of a database schema. These commands perform migration-related tasks. After creating models you can use these commands.
To manage database schema changes migrations are a great way. You will find Django has created migration files inside the migration folder for each model. Each table is mapped to the model.
Django has various commands to perform migration-related tasks. After creating models you can use these commands.
We have a model with attributes as given below -
//models.py from django.conf import settings from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) class Meta: db_table = "blog"
Let us create a migration for this model, use the below command and it will create a migration file inside the migration folder.
$ python3 manage.py makemigrations
After creating a migration, to reflect changes in the database permanently execute migrate command -
$ python3 manage.py migrate
To see raw SQL query executing behind applied migration execute the command -
$ sqlmigrate app-name migration-name (for example sqlmigrate blog 001)
To see app-specific migrations by specifying app-name, execute the command -
$ python3 manage.py showmigrations blog
To see all migrations, execute the command -
$ python3 manage.py showmigrations
A piece of information stored in the client browser is called cookies and itis used to store user's data in a file. Cookies can be stored permanently or for the specified time.
Cookies are removed automatically when expired. Django has built-in methods to set and fetch cookies.
The set_cookies() method can be used to set cookies. The getcookies() method can be used to get the cookies. The request.COOKIES['key'] array is used to get cookies value.
Let us see the example of Django Cookie -
Two functions setcookies() and getcookie() are used to set and get the cookie in views.py.
// views.py
from django.shortcuts import render
from django.http import HttpResponse
def setcookie(request):
response = HttpResponse("Cookie Set")
response.set_cookie('selenium-tutorial', 'nikasio.com')
return response
def getcookie(request):
tutorial = request.COOKIES['selenium-tutorial']
return HttpResponse("selenium tutorials @: "+ tutorial);Update URLs specified to access these functions -
//urls.py
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
path('scookie',views.setcookie),
path('gcookie',views.getcookie)
] Execute below command to start server -
Expect to come across this popular question in Django advanced interview questions.
Django is known for MVC(model, view, controller) web framework, but it can be used to build a backend that is an API.
Let us see step by step process for creating API
1. Installation
Install Django and Django REST Framework by creating a virtual environment.
$ pip install Django==1.9 $ pip install djangorestframework==3.6.3
Now create project tutorial and inside project create an app quickstart.
$ django-admin.py startproject tutorial $ cd samplelibrary $ django-admin.py startapp quickstart
Now let us create and apply schema migration by executing following -
$ python manage.py makemigrations $ python manage.py migrate
Now create a user with user name 'admin' and password 'password123'
python manage.py createsuperuser --email admin@example.com --username admin
2. Create Serializer
Serializers are used to convert data from one format to another. For example to convert formats like JSON, XML to complex data types like querysets and model instances and vice versa.
Now create a new module named tutorial/quickstart/serialisers.py for data presentations.
//serialisers.py
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')Here we are using hyperlinked relations with HyperlinkedModelSerializer as hyperlinking is good RESTful design.
3. Views
Viewsets are classes that provide the functionality of a set of views. Now create a UserViewSet class based on ModelViewSet in a views.py file of quickstart app.
//views.py
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializerRather than writing multiple views, here we are grouping together all the common behavior into classes called ViewSets.
4. URLs
Let us write up the API URLs.
//urls.py
from django.urls import include path
from rest_framework import routers
from tutorial.quickstart import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
# Wire up our API using automatic URL routing.
# for browsable API, we include login URLs.
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]Here we are using viewsets instead of views so that we can automatically generate the URL conf for our API by registering viewset with a router class.
Also, we are including a default login and logout view for use with browsable API.
5. Pagination
Pagination controls how many objects per page to return. Add below lines to settings.py
//settings.py
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
Settings
Now add 'rest_framework' to INSTALLED_APPS in settings module.
//settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#app
'quickstart',
#rest_framework
'rest_framework',
)Let us test the API we have built. start server from the command line.
$ python manage.py runserver
Now we can access our API from the command-line tool
curlbash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"email": "admin@example.com",
"groups": [],
"url": "http://127.0.0.1:8000/users/1/",
"username": "admin"
},
{
"email": "tim@example.com",
"groups": [ ],
"url": "http://127.0.0.1:8000/users/2/",
"username": "tim"
}
]
}