Accreditation Bodies
Accreditation Bodies
Accreditation Bodies
Supercharge your career with our Multi-Cloud Engineer Bootcamp
KNOW MOREDjango is a popular high-level web framework written in Python that follows the Model-View-Controller (MVC) architectural pattern. It provides a powerful and efficient way to build web applications with less code and time. It provides a lot of built-in features such as object-relational mapping (ORM), URL routing, template engine, authentication, database schema migrations, and many more. Whether you’re preparing for beginner's interview questions or appearing for a senior Django Developer, our set of Django interview questions and answers will help you appear for the interview more confidently.
Filter By
Clear all
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.
We know that all web application uses HTTP/HTTPS protocol. The basic principle of the HTTP protocol is Client sends a request to the server and the data server sends a response back to the client based on request data. We need a web server and WSGIserver while setting up a Django application on the server. Without a web server, WSGI server will result in a more number of requests resulting in gradually slow down the application performance. The web server will help in balancing the requests load on the server.
The client is a piece of software which sends a request by following HTTP/HTTPS protocol and mostly we consider Web Browser as a client. "Nginx, uWSGI and Django" or "Nginx, gunicorn and Django" or "Apache, mod_wsgi and Nginx" are the three types of combinations in Django application deployment on the server and we can use any one of the combinations. Now let us discuss on how a request is processed and response is created and sent to the client.
When a client sends request it first passed to a web server. The request contains configuration rules to be dispatch to the WSGI server. WSGI server sends the request to the Django application.
For dealing with request-response lifecycle, Django application has the following layers -
Any request that comes in is handled by Request middleware. There can be multiple middlewares and can find it in settings.py (project settings). While processing the request Django Request middlewares follow the order. Django has some default middlewares and we can also write or customize middleware. Middleware process the request and submits it to the URL Router or URL dispatcher.
URL Router receives a request from the middleware and from the request it collects the URL path. From the URL path, the URL router tries to match the request path with available URL patterns. These patterns are in the regular expression form. Once the URL path is matched with URL patterns the request is submitted to the View associated with URL.
Views are the business logic layer, which processes the business logic using request and request data. A request is processed in the view, it is sent to Context processor. Context processor adds context data that helps Template Renders to deliver the template to generate HTTP response and again this request will be sent back to Response middleware to process. Request middleware adds or modifies header information or body information before sending it to the client again.
Django is a free and open-source framework to develop web applications. Web development process becomes very easy and developer can focus only on designing process and boosts performance. Django follows the model-view-template architectural pattern. 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 faster and easier.
Django is a quick solution for web development. It has become the right platform for a customer for business and developers due to its ability to deliver high-quality code and transparent writing.
Batteries Included - Django comes with a collection of modules also know as Batteries. A lot of out of the box stuff, you may or may not use for your application comes with Django. Instead of writing your own code, just import the package you wish to use.
Wide range of topics are spanned in Django batteries which includes -
Django is an amazing framework, still, there are a few cons. The URL specifying with regular expressions is not an easy task. Template errors fail silently by default, to know that, you may waste a lot of time to figure out what’s wrong, or you might not even know that your application has a problem. Along with the advantages, there are many disadvantages to Django mentioned below.
Template Mistakes Flop Discreetly itself - System developers do not pay attention to mistakes when they undertake a class-based viewpoint and they are extended through inheritance.
Does Not Have The Capacity To Manage Different Requests At The Same Time:
Django does not support individual procedures to deal with many requests at the same time. Developers need to investigate approaches and make singular procedures to control various requests proficiently and rapidly at once.
Django is Excessively Monolithic: Django framework directs you into a given specific pattern.
Regex To Indicate Its URL: Django uses regex to determine its URL routing models, which makes the code bigger and makes convoluted syntaxes.
While Managing Backwards Compatibility, It’s Moving Extremely Gradually: Django has a tendency to get greater and heavier after some time. Django stresses more on dev profitability and backward compatibility than the speed.
There are many pros and cons of Django, still, when a project with a deadline is considered, using Django for the project provides the ultimate solution.
A common question in Django interview questions for freshers, don't miss this one.
Django architecture is based on the MVC pattern. MVC architecture solved lots of problems in the traditional approach of web development. The components of MVC pattern are Model, Views, and Control and is a product development architecture to solve the drawback of code of traditional approach.
1. Model: Model as a part of the web application, acts as a mediator between website interface and database, in short, it is the object that implements the logic for the application's data domain. Many times application only takes data in a particular dataset, and directly sends data to the view without any database, that dataset is called a model.
In Django architecture, the component model contains business logic. Let us see the example of website sign up, when you sign up, you are sending information to the controller which transfers it to models which apply business logic on it and stores in the database.
2. View: View component of Django architecture contains UI logic. It is a User Interface of the web application and contains HTML, CSS, and other front-end technologies. Contents for the UI comes from the Models component. When interacting with the specific component, a new Web page that is generated say due to click on any link of the website is the specific views that are stored and generated.
3. Controller: Controller component of the Django architecture is the main control component, that handles user interaction and selects view according to the model. The major task of the controller is according to the user interaction select a view component and applying to the model component.
4. MTV pattern - Django is an MTV (model-Template-View)framework and used template terminology for view and Views for Controller.
In the MVC pattern, a template is related to View and is a presentation layer that manages presentation logic and controls how to display and what content to display for the user.
It's no surprise that this one pops up often in interview questions on Django.
The Django follows "Batteries included" philosophy which provides almost everything developers want to try "out of the box". Everything you need to develop an application is part of the one product, and it works seamlessly together, and also follows consistent design principles.
Django’s working philosophy breaks into many components -
When a user sends a request on Django page:
The most common task in web application development is to write create, read, update and delete functionality (CRUD) for each table. It refers to the set of common operations that are used in web applications to interact with data from the database. It provides a CRUD interface that allows users to create, read, update or delete data in the application database.
Django helps us with its simplified implementation for CRUD operations using Function-Based views and class-based Views.
A common Django basic interview questions, don't miss this one.
Django is set up to communicate with SQlite a lightweight relational database. By default Django automatically creates an SQLite database. Django also supports PostgreSQL, MySQL, and Oracle.
Along with configuring Django to connect to a database you need to install the required Python packages to communicate with the database.
To connect to the database, Django configuration is done inside settings.py file of Django project in the DATABASES variable.
We will go step by step as follow to set up MySQL -
1) First Install MySQL Database Connector :
sudo apt-get install libmysqlclient-dev
2) Then Install the mysqlclient library using the following command :
pip install mysqlclient
3) Now Install MySQL server :
sudo apt-get install mysql-server
4) Create the Database :
i) First, verify that the MySQL service is running:
systemctl status mysql.service
ii) Log in with MySQL credentials using the following command where -u flag for declaring your username and -p flag that tells MySQL that this user requires a password :
mysql -u db_user -p
iii) Create a database
CREATE DATABASE db_name;
iv) Exit MySQL server, press
CTRL + D
5) Now add the MySQL Database Connection to Application:
i) Now edit the config file so that it has MySQL credentials. We will use vi to edit the file and add the following information:
sudo vi /etc/mysql/my.cnf database = db_name user = db_user password = db_password default-character-set = utf8
ii) Go to the settings.py file. Replace the current DATABASES lines with the following:
# Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': '/etc/mysql/my.cnf', }, }
i) Go to the settings.py file. Replace the current DATABASES lines with the following:
# 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' }, }
6) After file edit, need to restart MySQL for the changes to take effect :
systemctl daemon-reload systemctl restart MySQL
7) Now Test MySQL Connection to Application:
python manage.py runserver your-server-ip:8000
Django tried to support as many features as possible on all database backends still, not all database backends are the same, and we have to decide on which features to support and which assumption we can make safely.
Django officially supports three other popular relational databases.
Below is the list of relational databases supported by Django -
1. PostgreSQL
2. MySQL and
3. Oracle
Below is the list of databases to which Django supports connectivity -
4. SQLite - Django automatically creates an SQLite database for your project.
5. SAP (Sybase) SQL Anywhere
6. IBM DB2
7. Firebird
8. ADO- Microsoft SQL Server
9. ODBC - Microsoft SQL Server
10. Azure SQL database or other ODBC compatible database
Configuration to connect to the database is done in the settings.py file of the Django project.
ADO (ActiveX Data Objects) and ODBC (Open Database Connectivity) interfaces are standard for connecting to Microsoft SQL Server and is supported by most relational database brands.
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.
The Django Signals is a tactic to notify decoupled applications when certain events occur. The Django Signal is used when many pieces of code may be interested in the same events or when you need to interact with decoupled applications like A Django core model or A model defined by a third-party app.
Two key elements the Senders and the receivers are in the signals machinery. The sender is responsible to dispatch a signal, and the receiver is the one who receives this signal and then performs something.
A receiver can be a function or an instance method to receive signals. A sender can be a Python object or None to receive events from any sender.
Via the connect method, the connection between the receivers and senders is done through 'Signal Dispatchers', which are instances of Signal.
The Django core defines a ModelSignal, a subclass of Signal that allows the sender to lazily specify as a string of the app_label.ModelName form.
You need to register a receiver function that gets called when the signal is sent by using the Signal.connect() method to receive a signal.
Let us see a post_save built-in signal. The code for post_save is stored in the django.db.models.signals module. This signal is fired right after a model finishes executing its save method.
//models.py from django.contrib.auth.models import User from django.db.models.signals import post_save
def save_profile(sender, instance, **kwargs): instance.profile.save()
post_save.connect(save_profile, sender=User)
Here save_profile is a receiver, User is the sender and post_save is the signal. Wherever a User instance finalizes the execution of the save method, save_profile function will be executed.
A common question in Django interview questions for experienced, don't miss this one.
Django template engine is part of the Django framework and it is easy, extendible and handy in developing complex web applications.
A template is a text document or Python string marked-up using the Django template language. It can generate any text-based format like HTML, XML, CSV, ETC.
Being a web framework, Django requires a convenient way to generate HTML dynamically. A template is the most common approach to rely on. The template contains static parts of desired HTML output and some special syntax describing how dynamic content can be inserted.
A Django project can be configured with or without a template. You can configure one or more template engines. Django provides a standard API for loading or rendering templates irrespective of the backend. Loading template consists of searching the template for a given identifier and processing it and mostly compiling it into in-memory representation. Rendering means interpolating the template with context data and return the resulting string. django.template.Context is a context class and its constructor takes two arguments, one is a dictionary mapping variable name to variable values and second is the name of the current application.
The template contains variables and template is evaluated these variables get replaced with values.
Django has only one user type that is User. Users are differentiated on the basis of permissions you give. Any normal user can be authenticated and any user assigned the staff flat can log in to the contributed admin app. Users can be set active or de-active and only active users are allowed to log in. A superuser is just a convenient method to create a user with all permissions.
In Django, you easily create a superuser account to access the admin site.
We are assuming here that the project is created and database connection is set up, and you are in a project folder.
Now create an application by executing the command -
$ python manage.py startapp newapp
Register your newapp with the Django project say 'newproject'. Open settings.py in the code editor and update INSTALLED_APPS tuple and middleware tuple.
//settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'newapp', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', )
Now to access Admin Interface, initiate database by executing commands -
$ python manage.py makemigrations $ python manage.py migrate
Now create superuser by executing the command -
$ python manage.py createsuperuser
Wait for the success message and then enter the remaining user information.
We are assuming here that the project is created and database connection is set up, and you are in a project folder.
Your Djong application can be anywhere on your Python path. Here, we’ll create our app right next to your manage.py file so that it can be imported as its own top-level module, rather than a submodule of mysite.
To create an application, make sure you’re in the same directory here manage.py and type this command:
$ python manage.py startapp newapp
It will create a directory newapp, which would look like −
newapp/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py
Application newapp will house in this directory structure.
Now to write view open newapp/views.py file and update with below lines -
from django.http import HttpResponse def index(request): return HttpResponse("Hello, world")
To call this view, you need to map it to a URL.
Create URLconf in the newapp directory, create a file called urls.py. Your directory should look like -
newapp/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py urls.py views.py
Update urls.py file with the following code -
//urls.py from django.urls import path from.import views urlpatterns = [ path('', views.index, name='index'),]
Now point the root_URLconf at the newapps.urls module. In newsite/urls.py, import Django.urls.include and insert an include() in the urlpatterns list.
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('newapps/', include('newapps.urls')), path('admin/', admin.site.urls),]
ORM that is Object-Relational Mapping is a programming technique to convert data between the relational database and object-oriented programming languages such as Java, C#, etc. ORM maps database entities to Python code usually classes. You can construct your query in Python and it gets translated to SQL behind the scene.
For example instead of this SQL query -
SELECT * FROM <TABLE NAME>
you can use -
users = User.objects.all()
In SQL you have to execute that query using a driver, parse the result and then access the columns, but here ORM is doing that for you. That makes things easier and faster to use.
The most powerful feature of Django is its object-Relational Mapper that enables you to interact with the database.
Let us see the advantages of ORM -
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 = GroupSerializer
Rather 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" } ] }
“Django REST framework is a powerful and flexible toolkit used for building Web APIs”. Django REST Framework application easily a REST API into existing Django functionality and allows you to list all your API endpoints that inherit from Django REST Framework automatically. Django REST Framework is very easy to build model-backed APIs that have authentication policies and are browsable.
The purpose of the Django REST Framework is to work out of the box and it should take the minimum to install it. The REST framework is a funded project.
Some of the reasons why you should use the REST framework are :
Below is the REST framework requirement-
By default there are four main authentication methods are available -
1. SessionAuthentication - This authentication scheme uses Django's default session backend for authentication and it is appropriate for AJAX clients that are running in the same session context as your website.
If authentication is successful, it provides the following credentials -
Unauthenticated responses will result in an HTTP 403 Forbidden response.
2. BasicAuthentication - Basic authentication scheme uses HTTP Basic Authentication that is signed against a user's username and password. BasicAuthentication is appropriate for testing.
If authentication is successful, it provides the following credentials -
Unauthenticated responses will result in an HTTP 401 Unauthorized response with an appropriate WWW-Authenticate header.
3. TokenAuthentication - TokenAuthentication scheme uses a simple token-based HTTP authentication scheme and is suitable for client-server setups like native desktop or mobile client.
If authentication is successful, TokenAuthentication provides the following credentials.
Unauthenticated responses will result in an HTTP 401 Unauthorized response with an appropriate WWW-Authenticate header.
4. RemoteUserAuthentication - RemoteUserAuthentication scheme allows you to delegate authentication to your web server which sets the REMOTE_USERenvironment variable.
If authentication is successful, RemoteUserAuthentication providese following credentials -
In web application storing and retrieving information in the database is a common task. To perform these requirements Django comes with database management features. These features allow two things, one is, design database schema and second is, manage the data in the database that is read, write, update, delete, query, etc.
In Django, database tables are called models and these models are created in the models.py file which is located in the Dango app directory. A model is a python class. While defining model you need to give a class name, subclass it from Django's included models. Model class.
from Django.db import models class Glass(models.Model):
The model is valid only if it has one or more fields. Fields can be created by adding the attribute to the model class.
from django.db import models class Bottle(models.Model): size = models.IntegerField() color = models.CharField(max_length=100)
Here field name is 'size' and 'color'. models.IntegerField() is the instance for field class, and you are telling the database what kind of data you want to save in the field.
In the Django template, we can use the request processor to get the URL.
If you want to request a variable in the template, make sure you add 'django.template.context_processors.request' in your 'context_processors' settings. Also, do not forget to add other context processors you used in your application.
Till Django 1.9 version, by default, it comes configured. Default Template configuration is -
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
Use below line of code to get current path :
{{ request.path }}
Use below line of code to get current path with querystring:
{{ request.get_full_path }}
Use below line of code get Domain, path and querystring:
{{ request.build_absolute_uri }}
For example, suppose your URL is http://127.0.0.1:8000/home/?q=test
A simple way to create a user sign up is by using the UserCreationForm. Django provides a form 'UserCreationForm' inherited from ModelForm class to handle new user creation. The user creation form has three fields username, password1, and password2. Password2 is for password confirmation.
First, you have to import UserCreationForm to use it from django.contrib.auth.forms import UserCreationForm To handle the creation of users, Django does not provide any view, we have to create our own view.
So proceeding further to create user, here we are using project myproject and application myapp. To create user fist update urlpattern at the beginning of the urlpatterns list. Then create a new function in views.py to authenticate and save the user. The last step is to create an HTML template for the form display(view).
The User created, using 'UserCreationForm will have is_superuser and is_staff flag set to false but is_active flag set to True. UserCreationForm does not have an email field, so we can't email verification to the user to verify the account.
Session data is stored on the server. Django creates a random unique string called session-id or SID and Django associates that ID or SID with the data. As a value to the browser, the server sends a cookie named session-id containing SID as value. On-page request, the browser sends a request containing a cookie with SID to the server. To retrieve this session data and make it accessible in code, Django uses this SID. Django generated SID is 32 characters long random string. Django support for anonymous sessions. Django session framework allows to store and retrieve arbitrary data on per site visitor basis.
Seesions are implemented via middleware. To enable session functionality, edit MIDDLEWARE_CLASSES setting and make sure 'django.contrib.sessions.middleware.SessionMiddleware' is added.
Set the SESSION_ENGINE setting to "django.contrib.sessions.backends.file" to use file-based sessions. Also, set the SESSION_FILE_PATH setting to configure where Django store session files.
No, Django is not a Content Management System (CMS), rather it is a Web application framework and a programming tool that helps you to build websites.
DjangoCMS is a web publishing platform built with Django and offers out of the box support for the common features you expect from a CMS. Django CMS can be easily customized and extended by developers to create a site precise to their needs.
Django CMS is a thoroughly tested platform that supports both large and small web sites. Django CMS is robust internationalization support for creating multilingual sites. It can be configured to handle different requirements. Content editing is possible and provides rapid access to the content management interface. Django CMS supports a variety of editors with advanced text editing features. It is a flexible plugins system. Thorough documentation is available for Django CMS. Each published CMS page exists at two instances public and drat. An only draft version exists till you publish it.
A Mixin is a special type of inheritance in Python. It is gaining a big rise in Django / Web Application Development. Mexin can be used to allow classes in Python to share methods between any class that inherits from that Mixin.
A mixin or mix-in is a class that contains methods for use by other classes without having to be the parent class of those other classes. Sometimes Mixins are described as "included" rather than "inherited".
Django provides a number of mixins that provide more discrete functionality. Different type of mixins are -
Simple mixins are -
In Django, migrations are a way of propagating changes made in the model into the database schema. Django migrations can be created manually by running certain commands, but migrations automate the task of applying changes to the database. Django Migrations can be used as a version control system for database and Model. Migration keeps track of changes done in application Models/Table like adding a field, deleting a model, etc. Automatically generated migrations are used to apply changes to the database schema and to apply changes in data, you need to manually write the data migrations. Migrations in Django are stored as an on-disk format, referred to as “migration files”. These files are just like normal Python files with an agreed-upon object layout, written in a declarative style. Below is the format of a basic migration file:
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('migrations', '0001_initial')] operations = [ migrations.DeleteModel('Tribble'), migrations.AddField('Author', 'rating', models.IntegerField(default=0)), ]
To leverage MongoDB from Django, the following software should be installed and running -
Python
MongoDB
Django-norel - a version of Django designed for use with non-relational database engines
Django toolbox - Django-MongoDB engine depends on this general-purpose utility library
MongoDB-engine - MongoDB driver for Django
1. Create a project named 'testproj' with an application named 'testapp'.
django-admin.py startproject testproj
CD testproj/
django-admin.py startapp testapp
2. Setup - Configure following in settings.py
DATABASES = { 'default': { 'ENGINE': 'django_mongodb_engine', 'NAME': 'testdatabase', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '27017', 'SUPPORTS_TRANSACTIONS': False, }, }
3. Update models.py
from django.db import models class Article(models.Model): title = models.CharField(max_length = 64) content = models.TextField()
4. Save - Save model data from a Django view.
from django.http import HttpResponse from models import * def testview(request): article = Article(title = 'test title', content = 'test content' article.save() return HttpResponse("<h1>Saved!</h1>")
5. Execute javascript query like from Django view to check connection-
db.testapp_article.find()
6. Query MongoDB from Django to retrieve a list
articles = Article.objects.all()
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.
We know that all web application uses HTTP/HTTPS protocol. The basic principle of the HTTP protocol is Client sends a request to the server and the data server sends a response back to the client based on request data. We need a web server and WSGIserver while setting up a Django application on the server. Without a web server, WSGI server will result in a more number of requests resulting in gradually slow down the application performance. The web server will help in balancing the requests load on the server.
The client is a piece of software which sends a request by following HTTP/HTTPS protocol and mostly we consider Web Browser as a client. "Nginx, uWSGI and Django" or "Nginx, gunicorn and Django" or "Apache, mod_wsgi and Nginx" are the three types of combinations in Django application deployment on the server and we can use any one of the combinations. Now let us discuss on how a request is processed and response is created and sent to the client.
When a client sends request it first passed to a web server. The request contains configuration rules to be dispatch to the WSGI server. WSGI server sends the request to the Django application.
For dealing with request-response lifecycle, Django application has the following layers -
Any request that comes in is handled by Request middleware. There can be multiple middlewares and can find it in settings.py (project settings). While processing the request Django Request middlewares follow the order. Django has some default middlewares and we can also write or customize middleware. Middleware process the request and submits it to the URL Router or URL dispatcher.
URL Router receives a request from the middleware and from the request it collects the URL path. From the URL path, the URL router tries to match the request path with available URL patterns. These patterns are in the regular expression form. Once the URL path is matched with URL patterns the request is submitted to the View associated with URL.
Views are the business logic layer, which processes the business logic using request and request data. A request is processed in the view, it is sent to Context processor. Context processor adds context data that helps Template Renders to deliver the template to generate HTTP response and again this request will be sent back to Response middleware to process. Request middleware adds or modifies header information or body information before sending it to the client again.
Django is a free and open-source framework to develop web applications. Web development process becomes very easy and developer can focus only on designing process and boosts performance. Django follows the model-view-template architectural pattern. 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 faster and easier.
Django is a quick solution for web development. It has become the right platform for a customer for business and developers due to its ability to deliver high-quality code and transparent writing.
Batteries Included - Django comes with a collection of modules also know as Batteries. A lot of out of the box stuff, you may or may not use for your application comes with Django. Instead of writing your own code, just import the package you wish to use.
Wide range of topics are spanned in Django batteries which includes -
Django is an amazing framework, still, there are a few cons. The URL specifying with regular expressions is not an easy task. Template errors fail silently by default, to know that, you may waste a lot of time to figure out what’s wrong, or you might not even know that your application has a problem. Along with the advantages, there are many disadvantages to Django mentioned below.
Template Mistakes Flop Discreetly itself - System developers do not pay attention to mistakes when they undertake a class-based viewpoint and they are extended through inheritance.
Does Not Have The Capacity To Manage Different Requests At The Same Time:
Django does not support individual procedures to deal with many requests at the same time. Developers need to investigate approaches and make singular procedures to control various requests proficiently and rapidly at once.
Django is Excessively Monolithic: Django framework directs you into a given specific pattern.
Regex To Indicate Its URL: Django uses regex to determine its URL routing models, which makes the code bigger and makes convoluted syntaxes.
While Managing Backwards Compatibility, It’s Moving Extremely Gradually: Django has a tendency to get greater and heavier after some time. Django stresses more on dev profitability and backward compatibility than the speed.
There are many pros and cons of Django, still, when a project with a deadline is considered, using Django for the project provides the ultimate solution.
A common question in Django interview questions for freshers, don't miss this one.
Django architecture is based on the MVC pattern. MVC architecture solved lots of problems in the traditional approach of web development. The components of MVC pattern are Model, Views, and Control and is a product development architecture to solve the drawback of code of traditional approach.
1. Model: Model as a part of the web application, acts as a mediator between website interface and database, in short, it is the object that implements the logic for the application's data domain. Many times application only takes data in a particular dataset, and directly sends data to the view without any database, that dataset is called a model.
In Django architecture, the component model contains business logic. Let us see the example of website sign up, when you sign up, you are sending information to the controller which transfers it to models which apply business logic on it and stores in the database.
2. View: View component of Django architecture contains UI logic. It is a User Interface of the web application and contains HTML, CSS, and other front-end technologies. Contents for the UI comes from the Models component. When interacting with the specific component, a new Web page that is generated say due to click on any link of the website is the specific views that are stored and generated.
3. Controller: Controller component of the Django architecture is the main control component, that handles user interaction and selects view according to the model. The major task of the controller is according to the user interaction select a view component and applying to the model component.
4. MTV pattern - Django is an MTV (model-Template-View)framework and used template terminology for view and Views for Controller.
In the MVC pattern, a template is related to View and is a presentation layer that manages presentation logic and controls how to display and what content to display for the user.
It's no surprise that this one pops up often in interview questions on Django.
The Django follows "Batteries included" philosophy which provides almost everything developers want to try "out of the box". Everything you need to develop an application is part of the one product, and it works seamlessly together, and also follows consistent design principles.
Django’s working philosophy breaks into many components -
When a user sends a request on Django page:
The most common task in web application development is to write create, read, update and delete functionality (CRUD) for each table. It refers to the set of common operations that are used in web applications to interact with data from the database. It provides a CRUD interface that allows users to create, read, update or delete data in the application database.
Django helps us with its simplified implementation for CRUD operations using Function-Based views and class-based Views.
A common Django basic interview questions, don't miss this one.
Django is set up to communicate with SQlite a lightweight relational database. By default Django automatically creates an SQLite database. Django also supports PostgreSQL, MySQL, and Oracle.
Along with configuring Django to connect to a database you need to install the required Python packages to communicate with the database.
To connect to the database, Django configuration is done inside settings.py file of Django project in the DATABASES variable.
We will go step by step as follow to set up MySQL -
1) First Install MySQL Database Connector :
sudo apt-get install libmysqlclient-dev
2) Then Install the mysqlclient library using the following command :
pip install mysqlclient
3) Now Install MySQL server :
sudo apt-get install mysql-server
4) Create the Database :
i) First, verify that the MySQL service is running:
systemctl status mysql.service
ii) Log in with MySQL credentials using the following command where -u flag for declaring your username and -p flag that tells MySQL that this user requires a password :
mysql -u db_user -p
iii) Create a database
CREATE DATABASE db_name;
iv) Exit MySQL server, press
CTRL + D
5) Now add the MySQL Database Connection to Application:
i) Now edit the config file so that it has MySQL credentials. We will use vi to edit the file and add the following information:
sudo vi /etc/mysql/my.cnf database = db_name user = db_user password = db_password default-character-set = utf8
ii) Go to the settings.py file. Replace the current DATABASES lines with the following:
# Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': '/etc/mysql/my.cnf', }, }
i) Go to the settings.py file. Replace the current DATABASES lines with the following:
# 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' }, }
6) After file edit, need to restart MySQL for the changes to take effect :
systemctl daemon-reload systemctl restart MySQL
7) Now Test MySQL Connection to Application:
python manage.py runserver your-server-ip:8000
Django tried to support as many features as possible on all database backends still, not all database backends are the same, and we have to decide on which features to support and which assumption we can make safely.
Django officially supports three other popular relational databases.
Below is the list of relational databases supported by Django -
1. PostgreSQL
2. MySQL and
3. Oracle
Below is the list of databases to which Django supports connectivity -
4. SQLite - Django automatically creates an SQLite database for your project.
5. SAP (Sybase) SQL Anywhere
6. IBM DB2
7. Firebird
8. ADO- Microsoft SQL Server
9. ODBC - Microsoft SQL Server
10. Azure SQL database or other ODBC compatible database
Configuration to connect to the database is done in the settings.py file of the Django project.
ADO (ActiveX Data Objects) and ODBC (Open Database Connectivity) interfaces are standard for connecting to Microsoft SQL Server and is supported by most relational database brands.
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.
The Django Signals is a tactic to notify decoupled applications when certain events occur. The Django Signal is used when many pieces of code may be interested in the same events or when you need to interact with decoupled applications like A Django core model or A model defined by a third-party app.
Two key elements the Senders and the receivers are in the signals machinery. The sender is responsible to dispatch a signal, and the receiver is the one who receives this signal and then performs something.
A receiver can be a function or an instance method to receive signals. A sender can be a Python object or None to receive events from any sender.
Via the connect method, the connection between the receivers and senders is done through 'Signal Dispatchers', which are instances of Signal.
The Django core defines a ModelSignal, a subclass of Signal that allows the sender to lazily specify as a string of the app_label.ModelName form.
You need to register a receiver function that gets called when the signal is sent by using the Signal.connect() method to receive a signal.
Let us see a post_save built-in signal. The code for post_save is stored in the django.db.models.signals module. This signal is fired right after a model finishes executing its save method.
//models.py from django.contrib.auth.models import User from django.db.models.signals import post_save
def save_profile(sender, instance, **kwargs): instance.profile.save()
post_save.connect(save_profile, sender=User)
Here save_profile is a receiver, User is the sender and post_save is the signal. Wherever a User instance finalizes the execution of the save method, save_profile function will be executed.
A common question in Django interview questions for experienced, don't miss this one.
Django template engine is part of the Django framework and it is easy, extendible and handy in developing complex web applications.
A template is a text document or Python string marked-up using the Django template language. It can generate any text-based format like HTML, XML, CSV, ETC.
Being a web framework, Django requires a convenient way to generate HTML dynamically. A template is the most common approach to rely on. The template contains static parts of desired HTML output and some special syntax describing how dynamic content can be inserted.
A Django project can be configured with or without a template. You can configure one or more template engines. Django provides a standard API for loading or rendering templates irrespective of the backend. Loading template consists of searching the template for a given identifier and processing it and mostly compiling it into in-memory representation. Rendering means interpolating the template with context data and return the resulting string. django.template.Context is a context class and its constructor takes two arguments, one is a dictionary mapping variable name to variable values and second is the name of the current application.
The template contains variables and template is evaluated these variables get replaced with values.
Django has only one user type that is User. Users are differentiated on the basis of permissions you give. Any normal user can be authenticated and any user assigned the staff flat can log in to the contributed admin app. Users can be set active or de-active and only active users are allowed to log in. A superuser is just a convenient method to create a user with all permissions.
In Django, you easily create a superuser account to access the admin site.
We are assuming here that the project is created and database connection is set up, and you are in a project folder.
Now create an application by executing the command -
$ python manage.py startapp newapp
Register your newapp with the Django project say 'newproject'. Open settings.py in the code editor and update INSTALLED_APPS tuple and middleware tuple.
//settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'newapp', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', )
Now to access Admin Interface, initiate database by executing commands -
$ python manage.py makemigrations $ python manage.py migrate
Now create superuser by executing the command -
$ python manage.py createsuperuser
Wait for the success message and then enter the remaining user information.
We are assuming here that the project is created and database connection is set up, and you are in a project folder.
Your Djong application can be anywhere on your Python path. Here, we’ll create our app right next to your manage.py file so that it can be imported as its own top-level module, rather than a submodule of mysite.
To create an application, make sure you’re in the same directory here manage.py and type this command:
$ python manage.py startapp newapp
It will create a directory newapp, which would look like −
newapp/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py
Application newapp will house in this directory structure.
Now to write view open newapp/views.py file and update with below lines -
from django.http import HttpResponse def index(request): return HttpResponse("Hello, world")
To call this view, you need to map it to a URL.
Create URLconf in the newapp directory, create a file called urls.py. Your directory should look like -
newapp/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py urls.py views.py
Update urls.py file with the following code -
//urls.py from django.urls import path from.import views urlpatterns = [ path('', views.index, name='index'),]
Now point the root_URLconf at the newapps.urls module. In newsite/urls.py, import Django.urls.include and insert an include() in the urlpatterns list.
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('newapps/', include('newapps.urls')), path('admin/', admin.site.urls),]
ORM that is Object-Relational Mapping is a programming technique to convert data between the relational database and object-oriented programming languages such as Java, C#, etc. ORM maps database entities to Python code usually classes. You can construct your query in Python and it gets translated to SQL behind the scene.
For example instead of this SQL query -
SELECT * FROM <TABLE NAME>
you can use -
users = User.objects.all()
In SQL you have to execute that query using a driver, parse the result and then access the columns, but here ORM is doing that for you. That makes things easier and faster to use.
The most powerful feature of Django is its object-Relational Mapper that enables you to interact with the database.
Let us see the advantages of ORM -
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 = GroupSerializer
Rather 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" } ] }
“Django REST framework is a powerful and flexible toolkit used for building Web APIs”. Django REST Framework application easily a REST API into existing Django functionality and allows you to list all your API endpoints that inherit from Django REST Framework automatically. Django REST Framework is very easy to build model-backed APIs that have authentication policies and are browsable.
The purpose of the Django REST Framework is to work out of the box and it should take the minimum to install it. The REST framework is a funded project.
Some of the reasons why you should use the REST framework are :
Below is the REST framework requirement-
By default there are four main authentication methods are available -
1. SessionAuthentication - This authentication scheme uses Django's default session backend for authentication and it is appropriate for AJAX clients that are running in the same session context as your website.
If authentication is successful, it provides the following credentials -
Unauthenticated responses will result in an HTTP 403 Forbidden response.
2. BasicAuthentication - Basic authentication scheme uses HTTP Basic Authentication that is signed against a user's username and password. BasicAuthentication is appropriate for testing.
If authentication is successful, it provides the following credentials -
Unauthenticated responses will result in an HTTP 401 Unauthorized response with an appropriate WWW-Authenticate header.
3. TokenAuthentication - TokenAuthentication scheme uses a simple token-based HTTP authentication scheme and is suitable for client-server setups like native desktop or mobile client.
If authentication is successful, TokenAuthentication provides the following credentials.
Unauthenticated responses will result in an HTTP 401 Unauthorized response with an appropriate WWW-Authenticate header.
4. RemoteUserAuthentication - RemoteUserAuthentication scheme allows you to delegate authentication to your web server which sets the REMOTE_USERenvironment variable.
If authentication is successful, RemoteUserAuthentication providese following credentials -
In web application storing and retrieving information in the database is a common task. To perform these requirements Django comes with database management features. These features allow two things, one is, design database schema and second is, manage the data in the database that is read, write, update, delete, query, etc.
In Django, database tables are called models and these models are created in the models.py file which is located in the Dango app directory. A model is a python class. While defining model you need to give a class name, subclass it from Django's included models. Model class.
from Django.db import models class Glass(models.Model):
The model is valid only if it has one or more fields. Fields can be created by adding the attribute to the model class.
from django.db import models class Bottle(models.Model): size = models.IntegerField() color = models.CharField(max_length=100)
Here field name is 'size' and 'color'. models.IntegerField() is the instance for field class, and you are telling the database what kind of data you want to save in the field.
In the Django template, we can use the request processor to get the URL.
If you want to request a variable in the template, make sure you add 'django.template.context_processors.request' in your 'context_processors' settings. Also, do not forget to add other context processors you used in your application.
Till Django 1.9 version, by default, it comes configured. Default Template configuration is -
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
Use below line of code to get current path :
{{ request.path }}
Use below line of code to get current path with querystring:
{{ request.get_full_path }}
Use below line of code get Domain, path and querystring:
{{ request.build_absolute_uri }}
For example, suppose your URL is http://127.0.0.1:8000/home/?q=test
A simple way to create a user sign up is by using the UserCreationForm. Django provides a form 'UserCreationForm' inherited from ModelForm class to handle new user creation. The user creation form has three fields username, password1, and password2. Password2 is for password confirmation.
First, you have to import UserCreationForm to use it from django.contrib.auth.forms import UserCreationForm To handle the creation of users, Django does not provide any view, we have to create our own view.
So proceeding further to create user, here we are using project myproject and application myapp. To create user fist update urlpattern at the beginning of the urlpatterns list. Then create a new function in views.py to authenticate and save the user. The last step is to create an HTML template for the form display(view).
The User created, using 'UserCreationForm will have is_superuser and is_staff flag set to false but is_active flag set to True. UserCreationForm does not have an email field, so we can't email verification to the user to verify the account.
Session data is stored on the server. Django creates a random unique string called session-id or SID and Django associates that ID or SID with the data. As a value to the browser, the server sends a cookie named session-id containing SID as value. On-page request, the browser sends a request containing a cookie with SID to the server. To retrieve this session data and make it accessible in code, Django uses this SID. Django generated SID is 32 characters long random string. Django support for anonymous sessions. Django session framework allows to store and retrieve arbitrary data on per site visitor basis.
Seesions are implemented via middleware. To enable session functionality, edit MIDDLEWARE_CLASSES setting and make sure 'django.contrib.sessions.middleware.SessionMiddleware' is added.
Set the SESSION_ENGINE setting to "django.contrib.sessions.backends.file" to use file-based sessions. Also, set the SESSION_FILE_PATH setting to configure where Django store session files.
No, Django is not a Content Management System (CMS), rather it is a Web application framework and a programming tool that helps you to build websites.
DjangoCMS is a web publishing platform built with Django and offers out of the box support for the common features you expect from a CMS. Django CMS can be easily customized and extended by developers to create a site precise to their needs.
Django CMS is a thoroughly tested platform that supports both large and small web sites. Django CMS is robust internationalization support for creating multilingual sites. It can be configured to handle different requirements. Content editing is possible and provides rapid access to the content management interface. Django CMS supports a variety of editors with advanced text editing features. It is a flexible plugins system. Thorough documentation is available for Django CMS. Each published CMS page exists at two instances public and drat. An only draft version exists till you publish it.
A Mixin is a special type of inheritance in Python. It is gaining a big rise in Django / Web Application Development. Mexin can be used to allow classes in Python to share methods between any class that inherits from that Mixin.
A mixin or mix-in is a class that contains methods for use by other classes without having to be the parent class of those other classes. Sometimes Mixins are described as "included" rather than "inherited".
Django provides a number of mixins that provide more discrete functionality. Different type of mixins are -
Simple mixins are -
In Django, migrations are a way of propagating changes made in the model into the database schema. Django migrations can be created manually by running certain commands, but migrations automate the task of applying changes to the database. Django Migrations can be used as a version control system for database and Model. Migration keeps track of changes done in application Models/Table like adding a field, deleting a model, etc. Automatically generated migrations are used to apply changes to the database schema and to apply changes in data, you need to manually write the data migrations. Migrations in Django are stored as an on-disk format, referred to as “migration files”. These files are just like normal Python files with an agreed-upon object layout, written in a declarative style. Below is the format of a basic migration file:
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('migrations', '0001_initial')] operations = [ migrations.DeleteModel('Tribble'), migrations.AddField('Author', 'rating', models.IntegerField(default=0)), ]
To leverage MongoDB from Django, the following software should be installed and running -
Python
MongoDB
Django-norel - a version of Django designed for use with non-relational database engines
Django toolbox - Django-MongoDB engine depends on this general-purpose utility library
MongoDB-engine - MongoDB driver for Django
1. Create a project named 'testproj' with an application named 'testapp'.
django-admin.py startproject testproj
CD testproj/
django-admin.py startapp testapp
2. Setup - Configure following in settings.py
DATABASES = { 'default': { 'ENGINE': 'django_mongodb_engine', 'NAME': 'testdatabase', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '27017', 'SUPPORTS_TRANSACTIONS': False, }, }
3. Update models.py
from django.db import models class Article(models.Model): title = models.CharField(max_length = 64) content = models.TextField()
4. Save - Save model data from a Django view.
from django.http import HttpResponse from models import * def testview(request): article = Article(title = 'test title', content = 'test content' article.save() return HttpResponse("<h1>Saved!</h1>")
5. Execute javascript query like from Django view to check connection-
db.testapp_article.find()
6. Query MongoDB from Django to retrieve a list
articles = Article.objects.all()
Django is a free, open-source web framework written in Python programming language. This framework is based on Model-View-Template (MVT) architectural patterns. Django is a high-level framework that motivates fast, clean development and pragmatic design. Django is popular due to the friendly features it offers to both beginners and advanced developers. Django makes it easier to build web applications with less code complexity. The framework is robust and can be used for building any kind of website worldwide.
Django is designed to handle the challenges like-
Today, Django is being used to develop the top website categories like Business & Industry, Arts & Entertainment, Shopping, Internet & Telecom and so on. To learn more about Django, enroll in our Django Course, which will help you better prepare for the interview.
If you are seeking to make a career in Django, you may encounter plenty of Django interview questions and answers during the interview. Preparing for a Django interview can be difficult. However, these expert-authored Django interview questions and answers can be made easier. If you want to develop more skills in web development, join our web development course with a certificate and upskill your career.
These top interview questions and answers in Django can benefit freshers and experienced individuals alike. Also, Django interview questions will clarify your concepts and help you crack the interview and land your dream job.
Submitted questions and answers are subjecct to review and editing,and may or may not be selected for posting, at the sole discretion of Knowledgehut.
Get a 1:1 Mentorship call with our Career Advisor
By tapping submit, you agree to KnowledgeHut Privacy Policy and Terms & Conditions