Django Framework Interview Question And
Answer
Md Naimur Rahman
1. What is Django?
1. Framework: Django is a high-level web framework for building web applications in Python.
2. Architecture: It follows the Model-View-Template (MVT) pattern, similar to the Model-View-Controller (MVC) pattern.
3. Features:
 ORM: Built-in Object-Relational Mapping for database interaction.
 Admin Interface: Automatic admin interface for managing database records.
 URL Routing: Flexible system for mapping URLs to views.
 Template Engine: Built-in for defining and rendering HTML templates.
 Security: Includes protections against common web vulnerabilities.
 Authentication and Authorization: Robust tools for user management and permissions.
 Middleware: Allows global processing of requests and responses.
 Testing Support: Framework for easy development and execution of tests.
4. Philosophy: Django emphasizes rapid development, clean code, and follows the "Convention over Configuration" philosophy.
5. Usage: Widely used for projects of various sizes, from small to large-scale applications.
6. Principles: Promotes reusability, modularity, and adheres to the "Don't Repeat Yourself" (DRY) principle.
2
2. Difference Between a Project & App in Django?
Aspect Django Project Django App
Definition Represents the entire web application. A self-contained module handling a specific functionality.
Functionality
Contains overall settings, configurations, and
multiple apps.
Encapsulates specific aspects like models, views, and
templates.
Example A project named "MyBlog" for an entire blog website.
Apps within "MyBlog" for functionalities like "Blog," "User
Authentication," and "Comments."
Hierarchy Top-level container tying together multiple apps.
Modular component designed for a specific feature or
functionality.
Reusability Typically not reused in other projects.
Intended to be reusable and can be plugged into different
projects.
Relationship One project can have multiple apps. An app is a component within a project.
3
3. How do we initialize a project and app in Django ?
Step Command Description
1 pip install Django Install Django using pip.
2
django-admin startproject
projectname
Create a Django project. Replace "projectname" with your desired project
name.
3 cd projectname Navigate to the project directory.
4 python manage.py startapp appname
Create a Django app within the project. Replace "appname" with your desired
app name.
5
Update INSTALLED_APPS in
settings.py
Add your app to the INSTALLED_APPS list in the project's settings.
6 python manage.py makemigrations Create database migration files.
7 python manage.py migrate Apply migrations to create database tables.
8 python manage.py runserver Start the development server at http://127.0.0.1:8000/.
9 python manage.py createsuperuser Create a superuser for the admin panel.
10
Admin Panel:
http://127.0.0.1:8000/admin/
Access the admin panel using the superuser credentials.
4
4. How do we start our development server in Django?
To start the development server in Django:
1. Open a terminal/command prompt in your project directory.
2. Run python manage.py runserver (or python3 for Python 3).
3. The default server address is http://127.0.0.1:8000/.
4. Access your Django app in a web browser.
5. For a custom host/port, use python manage.py runserver <host>:<port>.(python
manage.py runserver 0.0.0.0:8080)
6. Development server is for testing, not for production; use Gunicorn/uWSGI with Nginx/Apache in
production.
5
5. What does the settings.py file do?
The settings.py file in Django is a crucial configuration file for web applications. Key elements
include:
1. Database Configuration: Specifies database details.
2. Debug Mode: Controls debug behavior.
3. Static and Media Files: Defines directories for static and media files.
4. Installed Apps: Lists active applications.
5. Middleware: Configures middleware components.
6. Template Configuration: Settings for template engines.
7. Timezone and Language: Sets default timezone and language.
8. Authentication and Authorization: Configures user authentication and authorization.
9. Security: Settings for enhancing application security.
10.Logging Configuration: Defines how the application logs messages.
11.Custom Settings: Allows developers to add project-specific configurations.
6
6. What are models? What are views? What are templates?
Component Definition Responsibilities
Models
Represent data structure, handle
database operations.
- Define structure of database tables.
- Encapsulate logic for CRUD operations on the database.
Views
Handle presentation logic and user
interface.
- Process user requests.
- Interact with models to retrieve data.
- Return data to templates for rendering.
Templates
Responsible for presenting and rendering
data.
- Define structure of the final HTML or markup.
- Use placeholders and control structures to insert data
dynamically.
7
7. What are url patterns?
In Django, URL patterns are typically configured in the urls.py file within each app of a project.
Here's a breakdown:
 URL Patterns: Fundamental in web development frameworks like Django.
 Definition: Determine how incoming URLs are matched to views or functions.
 Configuration: Defined in the urls.py file within each app.
 Mapping to Views: Associate URL patterns with specific views or view functions.
 Hierarchical Structure: Allows for organized and modular URL routing, supporting parameters.
 Inclusion: Enables the composition of larger applications from smaller, reusable components.
# In app/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('home/', views.home, name='home'),
path('blog/<int:post_id>/', views.blog_detail, name='blog_detail'),
]
8
9. What is the Django Admin panel?
 Django Admin Panel Overview:
 Built-in feature of Django web framework.
 Provides a graphical interface for managing application data.
 Functionality:
 Enables CRUD operations (Create, Read, Update, Delete) on models.
 No need for custom views; automates data management tasks.
 Key Features:
 Highly customizable: developers can define display and edit preferences.
 Incorporates robust security measures for authorized access.
 Automatically generates user interface based on model definitions.
 Integration with Models:
 Seamless integration with Django models.
 Leverages model information for form generation and data display.
 Usage:
 Register models with the admin site to enable admin functionality.
 Accessible through a specified URL for efficient data management.
9
9. What is Make migrations & migrate command?
Django in Python, the terms "make migrations" and "migrate" are related to database
management:
 Make Migrations:
 Generates migration files capturing changes to the database schema.
 Examines Django models and creates migration files accordingly.
 Command: python manage.py makemigrations.
 Migrate:
 Applies migration files to update the actual database schema.
 Reads migration files and executes SQL statements or database-specific commands.
 Ensures synchronization between code models and database structure.
 Command: python manage.py migrate.
10
10. What is FBV vs CBV in Django?
Aspect Function-Based Views (FBV) Class-Based Views (CBV)
Implementation Implemented as Python functions.
Implemented as Python classes, with
methods for different HTTP methods.
Readability and Simplicity Generally simpler and more straightforward.
May have a steeper learning curve but
provides a more organized structure.
Reusability
Functions are less reusable unless explicitly designed as
such.
Classes and inheritance allow for better
code reuse and organization.
Organization and Structure May become less organized for complex views.
Offers a more structured approach, making
it easier to organize code.
Flexibility and Extensibility
May require additional decorators for functionality
extension.
Easily extendable through inheritance and
mixins.
Common Patterns Explicit handling of HTTP methods through conditionals.
Django provides mixin classes and generic
views for common patterns.
# views.py
from django.shortcuts import render
def my_fbv(request):
# View logic for handling the request
return render(request, 'my_template.html')
# views.py
from django.views import View
from django.shortcuts import render
class MyCBV(View):
def get(self, request):
# View logic for handling GET requests
return render(request, 'my_template.html')
11
11. What is MEDIA_ROOT
1. Definition: MEDIA_ROOT is a setting in Django used to specify the absolute filesystem path to the
directory where user-uploaded media files are stored.
2. Purpose: It facilitates the management of user-uploaded content, such as images and videos, by
determining the location on the server's file system where these files are saved.
3. Configuration: MEDIA_ROOT is typically configured in the settings.py file of a Django project. It is used
in conjunction with the MEDIA_URL setting, which defines the base URL for serving media files.
4. Example Configuration:
5. File Serving: It's important to configure the web server to handle requests for media files and point it to the
specified MEDIA_ROOT directory when deploying a Django project in a production environment.
6. Usage: Once configured, Django uses MEDIA_ROOT to store user-uploaded media files, and MEDIA_URL
to generate URLs for serving these files to users.
# settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
12
12. What does "python manage.py collectstatic" do?
1. Purpose: collectstatic is a Django management command designed to gather static files (such as CSS,
JavaScript, and images) from various apps within a Django project.
2. Collection Process: It collects static files from each app's static directory, taking into account potential
naming conflicts.
3. Single Directory: The collected static files are combined into a single directory specified by the
STATIC_ROOT setting in the project's settings.py file.
4. Deployment: This command is crucial during the deployment of a Django project, as it ensures that all
necessary static files are organized in one location, making it easier to serve them efficiently.
5. Avoids Naming Conflicts: In case of identical filenames across apps, collectstatic appends unique identifiers
to prevent naming conflicts.
6. Configuration Example:
# settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') 13
13. Serving static files during production?
1. Configure STATIC_ROOT:
 Set the STATIC_ROOT setting in the settings.py file to specify the absolute filesystem path where collected static files will
be stored.
2. Run collectstatic Command:
 Execute python manage.py collectstatic to gather static files from apps into the directory specified by STATIC_ROOT.
3. Web Server Configuration:
 Configure your web server (e.g., Nginx, Apache) to serve static files directly.
 For Nginx, use the alias directive.
 For Apache, use the Alias directive.
4. CDN Usage:
 Consider using a Content Delivery Network (CDN) to cache and distribute static files globally, improving delivery speed.
5. Compression:
 Enable compression for static files to reduce bandwidth usage and enhance loading times.
6. Security Considerations:
 Review and adjust security settings on the web server to restrict access and prevent unauthorized downloads of static files.
7. Separation of Static and Media Files:
 Distinguish between static files (CSS, JavaScript) and media files (user uploads) using STATIC_URL and MEDIA_URL
settings.
14
14. What are CSRF Tokens?
CSRF Tokens:
1. Purpose:
 CSRF (Cross-Site Request Forgery) tokens are a security measure to protect web applications against
malicious CSRF attacks.
2. Generation:
 When a user authenticates, the server generates a unique and random CSRF token for the session.
3. Inclusion in Forms:
 CSRF tokens are included in forms as hidden fields or in headers of HTTP requests.
4. Verification on Submission:
 When a form is submitted, the server checks whether the CSRF token in the request matches the one
associated with the user's session.
5. Protection Mechanism:
 CSRF tokens prevent attackers from tricking users into making unintended and unauthorized requests
by requiring the inclusion of a unique token in each form
15
15. What is DRF?
 DRF Overview:
 Django Rest Framework (DRF) is a toolkit for building Web APIs in Django.
 Key Features:
 Serialization:
 Converts complex data types into Python data for easy rendering into JSON.
 Views:
 Class-based views tailored for handling HTTP methods in API endpoints.
 Authentication and Permissions:
 Supports various authentication methods and permission controls.
 ViewSets:
 Classes combining logic for handling HTTP methods, promoting code reuse.
 Routers:
 Automatically wires up API views to URLs, reducing boilerplate code.
 Browsable API:
 Provides a browsable API for easy exploration and interaction.
 Pagination:
 Built-in support for efficiently paginating large data sets in API responses.
 Usage:
 Installed as a Django app, configured in the project for streamlined API development.
 Benefits:
 Widely used, well-documented, and offers flexibility in RESTful API development.
16
16. What are Django Signals?
Django Signals:
 Definition:
 Django signals are a messaging mechanism facilitating communication between decoupled components in a Django
application.
 Components:
 Sender:
 Object triggering a signal.
 Signal:
 Messaging mechanism using django.dispatch.Signal.
 Receiver:
 Function responding to a signal.
 Connecting:
 Signals and receivers are connected using @receiver decorator or signal.connect() method.
 Built-in Signals:
 Django has built-in signals, like post_save, allowing customization and extension of default behavior.
 Example:
 Connect a function to the post_save signal of the User model to execute actions when a user is created or updated.
 Benefits:
 Promotes decoupling, modularization, and reusability in Django applications.
17
17. What are Model Serializers?
Model Serializers in Django Rest Framework (DRF):
 Definition:
 Specialized serializers in DRF for converting Django models to Python data types
suitable for serialization.
 Usage:
 Inherit from serializers.ModelSerializer and specify the model and fields. Automatic
field inference reduces explicit definitions.
 Functionality:
 Handles validation during deserialization and facilitates creating or updating model
instances.
18
18. Explain how a request is processed in Django?
In Django, the request processing involves the following steps:
1. URL Dispatching:
 Maps the requested URL to a view function using URL patterns.
2. View Function:
 Processes the request, interacts with models, and returns an HTTP
response.
3. Middleware Processing:
 Global processing of requests and responses, before and after the view.
4. Template Rendering:
 If applicable, generates dynamic HTML content using Django's template
engine.
5. Response Object:
 The view returns an instance of an HTTP response class.
6. Middleware Processing (post-view):
 Additional processing or modifications to the response.
7. Sending the Response:
 The processed response is sent back to the client, completing the
request-response cycle.
19
19. Why is Django called a loosely coupled framework?
Django is often referred to as a "loosely coupled" framework due to its design philosophy and architecture that promotes modularity,
flexibility, and the separation of concerns. Here are some reasons why Django is considered loosely coupled:
o Modular Components:
o Django is comprised of modular components that can be used independently.
o Developers can selectively utilize features like ORM, templating, and
authentication without committing to the entire framework.
o Reusable Apps:
o Encourages the creation of reusable apps for specific functionalities.
o Apps are self-contained, promoting code reusability and easy integration into
different projects.
o Separation of Concerns:
o Follows the MVC (or MTV) architectural pattern, separating business logic
(models), presentation (views/templates), and data handling.
o Allows for organized and clear code structure.
o Configurable Settings:
o Django provides a settings module for project-specific configurations.
o Developers can customize settings without tightly coupling their applications
to the core framework.
o Middleware Flexibility:
o Middleware components enable global processing of
requests and responses.
o Developers can add or remove middleware based on
project requirements, allowing for customization
without tightly coupling to the framework.
o Flexible Database Backbends:
o Django's ORM offers an abstraction layer for database
interactions.
o Supports various database backbends, providing
flexibility for developers to choose based on project
needs.
o Pluggable Authentication:
o Offers a pluggable authentication system.
o Developers can customize or replace authentication
mechanisms, adapting them to specific application
requirements.
20
20. Explain the Migration in Django.
 Purpose: Manage database schema changes over time.
 Process:
 Create an initial migration capturing current model state.
 Use makemigrations to generate migration files based on model changes.
 Apply migrations with migrate to update the database schema.
 Migration Files: Python scripts in the migrations directory of each app.
 Commands:
 makemigrations: Generates migration files.
 migrate: Applies pending migrations to the database.
 Rollback: Use migrate with a specific migration name or python manage.py migrate app_name zero to
revert migrations.
 History: Migrations are recorded in the django_migrations table for tracking
21
21. What is Django ORM?
 Object-Relational Mapping (ORM):
 Django ORM is a component of the Django web framework.
 It facilitates interaction with relational databases using an object-
oriented approach.
 Models:
 Models are defined as Python classes in Django ORM.
 Each model class corresponds to a database table, and class
attributes represent table fields.
 Database Migration:
 Django provides a migration system for evolving database
schemas.
 Developers can make changes to models, and Django handles the
creation and updating of database tables.
 Querysets:
 Django ORM uses Querysets, which are Pythonic APIs for
database queries.
 Allows filtering, ordering, and aggregating data in a way
that resembles SQL but is written in Python.
 Automatic Admin Interface:
 Django automatically generates a web-based admin
interface for models.
 This interface simplifies data management during
development and testing.
 Productivity and Maintainability:
 Django ORM abstracts the complexities of database
interactions, allowing developers to focus on application
logic.
 Enhances productivity by reducing the need for manual
SQL queries and providing a higher-level interface.
22
22. Difference between select_related and prefetch_related in Django?
Feature select_related prefetch_related
Use Case ForeignKey and OneToOneField relationships
Many-to-many and reverse
ForeignKey/OneToOneField relationships
Query Strategy
Performs a SQL join, includes related fields in the SELECT
statement
Does separate lookups for each
relationship, fetches related objects, and
does mapping in Python
Efficiency
More efficient for ForeignKey and OneToOneField
relationships
More efficient for many-to-many and
reverse ForeignKey/OneToOneField
relationships
Number of Queries
Reduces the number of queries by fetching related objects
in a single query
Reduces the number of queries by
fetching all related objects in a single
query
Example
python
Book.objects.select_related('author').get(id=1).author
python
Author.objects.prefetch_related('book_set'
).get(id=1).book_set.all()
23
23. Difference between Emp.object.filter(), Emp.object.get() and Emp.objects.all()
in Django Queryset?
Feature Emp.objects.filter() Emp.objects.get() Emp.objects.all()
Purpose
Retrieve a set of objects matching
criteria
Retrieve a single object based
on specific criteria
Retrieve all objects of a
particular model
Returned Type
QuerySet (can contain multiple
objects)
Single model instance
QuerySet (contains all
instances of the model)
Exception Handling
Does not raise exceptions if no match
is found
Raises DoesNotExist if no
match is found, Raises
MultipleObjectsReturned if
more than one match is found
Does not raise exceptions
Example
Emp.objects.filter(job_title='Develope
r')
Emp.objects.get(id=1) Emp.objects.all()
24
24. Which Companies Use Django?
1.Instagram: One of the largest social media platforms for sharing photos and videos.
2.Pinterest: A popular visual discovery and bookmarking platform.
3.Disqus: A platform for web comments and discussions.
4.Spotify: A leading music streaming service.
5.Dropbox: A cloud storage and collaboration platform.
6.Mozilla: The organization behind the Firefox web browser.
7.NASA: The National Aeronautics and Space Administration uses Django for some of its web
applications.
8.Eventbrite: An online event management and ticketing platform.
9.Bitbucket: A Git repository hosting service.
10.The Washington Post: A major American newspaper.
11.Reddit: Parts of Reddit's infrastructure use Django.
25
25. What is the difference between Flask, Pyramid, and Django?
Feature Flask Pyramid Django
Philosophy Micro framework, simplicity,
flexibility
Modular, flexible, "use what
you need" approach
Batteries-included, rapid development,
convention over configuration
Complexity Lightweight and minimalistic Moderate complexity, scalable
for various projects
High-level, comprehensive, includes many
built-in features
Architecture
Pattern
No strict adherence, flexible Flexible, supports different
architectural patterns
MTV (Model-Template-View)
ORM Not included by default, can be
added
Not included by default, can
be integrated with various
ORMs
Django ORM included, tightly integrated
Template Engine Jinja2 Mako, Chameleon, Jinja2
(choice of templating engines)
Django Template Language (DTL)
Authentication Not built-in, can be added through
extensions
Built-in authentication system Built-in authentication system, user
management
Admin Interface No built-in admin interface No built-in admin interface
(can be added)
Powerful built-in admin interface
Flexibility Highly flexible, more manual
configuration
Flexible, modular, choose
components as needed
More opinionated, less flexibility, more
conventions
Community
Support
Active community, large number of
extensions
Active community, modular
design encourages
contributions
Large and active community, extensive
documentation
Use Cases Small to medium-sized projects,
APIs
Wide range of projects,
scalable
Medium to large-sized projects, content-
heavy websites, applications with built-in
admin interfaces
26
26.What are the advantages/disadvantages of using Django?
Advantages of Django Disadvantages of Django
High-level Abstraction Learning Curve
Rapid Development Monolithic Structure
ORM (Object-Relational Mapping) Overhead
Admin Interface Template System
Security Features Opinionated
Versatility API Complexity
Community and Documentation
Scalability
27
27. What Is The Difference Between Authentication And Authorization
Aspect Authentication Authorization
Focus Verifying the identity of a user or system.
Determining access rights based on the
authenticated identity.
Purpose Ensures the user is who they claim to be.
Regulates access to resources based on
user permissions.
Verification vs. Permission
Involves verifying identity credentials (e.g.,
username and password).
Involves checking permissions associated
with an authenticated identity.
Example
Verifying login credentials (username and
password).
Allowing access to specific pages or actions
based on user roles.
Process Flow The initial step in the access control process.
Follows authentication and determines
access levels.
28
28. What Is Django.Shortcuts.Render Function?
1. Purpose: django.shortcuts.render simplifies the rendering of HTML templates within Django views.
2. Parameters:
 request: Represents the HTTP request object.
 template_name: Specifies the name or path of the template file to be rendered.
 context: A dictionary containing data to be passed to the template for rendering.
3. Usage Example:
from django.shortcuts import render
def my_view(request):
data = {'key': 'value'}
return render(request, 'my_template.html', context=data)
4. Convenience: Provides a convenient way to generate HTML responses by handling the rendering process and
context data.
5. Code Organization: Promotes separation of concerns by keeping view logic separate from template rendering in
Django applications.
29
29. What Aim Q Objects In Django ORM?
In Django ORM, a Q object is a tool that helps make database queries more flexible and dynamic. Here's a simpler explanation:
Complex Queries:
Purpose: Q objects let you create queries with multiple conditions, combining
them using AND, OR, and NOT.
Example:
from django.db.models import Q # Find books published after 2000 or
authored by a specific author Book.objects.filter(Q(pub_date__gt='2000-
01-01') | Q(author='John Doe'))
Logical Operators:
Purpose: Q objects support logical AND, OR, and NOT, allowing you to build
more intricate query conditions.
Example:
from django.db.models import Q # Find books published after 2000 and
authored by a specific author Book.objects.filter(Q(pub_date__gt='2000-
01-01') & Q(author='John Doe'))
Dynamic Query Building:
Purpose: Q objects are handy for creating queries based on changing
conditions, like user input.
Example:
from django.db.models import Q # Dynamic query based on author and
publication date def dynamic_book_query(author, pub_date): query = Q()
if author: query &= Q(author=author) if pub_date: query &=
Q(pub_date__gt=pub_date) return Book.objects.filter(query)
Combining Queries:
Purpose: Q objects can be combined for more
complex queries by nesting or using logical
operators.
Example:
from django.db.models import Q # Find
books published after 2000 and
authored by John Doe or Jane Doe
Book.objects.filter(Q(pub_date__gt='2
000-01-01') & (Q(author='John Doe') |
Q(author='Jane Doe')))
Readability and Maintainability:
Purpose: Q objects make queries easier to read,
especially with multiple conditions, improving code
maintainability.
Example:
from django.db.models import Q #
Query with multiple conditions using
Q objects
Book.objects.filter(Q(pub_date__gt='2
000-01-01') | (Q(author='John Doe)
30
30. What Is The Significance Of The Manage.Py File In Django?
Functionality Description Example
Command Line Interface Provides a command-line interface for Django-related tasks. python manage.py runserver
Database Migrations
Manages database migrations for applying, unapplying, and
inspecting changes to the database schema over time.
python manage.py migrate
Create Superuser
Allows the creation of a superuser account for accessing the
Django admin interface.
python manage.py createsuperuser
Django Shell
Launches an interactive Python shell with the Django
environment pre-loaded.
python manage.py shell
Testing Runs tests for the Django project to ensure code correctness. python manage.py test
Custom Commands
Supports the creation and execution of custom management
commands.
python manage.py
my_custom_command
Static Files Collection
Collects static files from apps into a single directory during
deployment.
python manage.py collectstatic
Project Configuration
Reads the project's settings and configuration, serving as the
starting point for many Django operations.
python manage.py diffsettings
31
31. What Is The Use Of The Include Function In The Urls.Py File
1. Inclusion of URL Patterns: include function is used in Django's urls.py to include URL patterns from other files
or apps into the main project.
2. Modularization: It promotes modularization by allowing the separation of URL patterns into distinct files,
enhancing code organization.
3. Organized Code Structure: By using include, the main urls.py file remains cleaner and more focused,
improving readability and maintainability.
4. Reuse of Patterns: Enables the reuse of URL patterns across different components of the Django project,
fostering code efficiency.
5. Example Usage:
# project/urls.py
from django.urls import path, include
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls')),
# other URL patterns for the main project
]
# myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('some-view/', views.some_view,
name='some_view'),
# other URL patterns for the 'myapp' app
]
32
32. What Does {% Include %} Do In Django?
1. Inclusion of Template Content: {% include %} is a Django template tag used to embed the content of another
template within the current template.
2. Modularization: Enables modularization of template code by allowing the reuse of common components in different
templates.
3. Reduction of Redundancy: Reduces redundancy by centralizing common content in separate templates and including
them where needed.
4. Example Usage:
Html <!-- main_template.html --> <div> <h1>Main Content</h1> </div> <div> {% include
'included_template.html' %} </div>
html
<!-- included_template.html --> <p>This content is included in the main template.</p>
5. Enhanced Maintainability: Promotes maintainability by allowing changes to be made in a single included template,
reflecting updates across multiple locations where it is included.
Top of Form
33
33. What is a Middleware in Django?
• Definition:
 Middleware in Django is a mechanism to process requests and responses globally in a Django web application.
• Functionality:
 Middleware classes execute before or after the view processes the request, allowing for global actions on incoming
requests or outgoing responses.
• Chain of Classes:
 Middleware functions as a chain of classes, each designed for specific tasks like authentication, security, logging, or
request/response modification.
• Order of Execution:
 Middleware classes are executed in a specific order as defined in the MIDDLEWARE setting in the project's settings.py
file.
• Common Use Cases:
 Authentication Middleware: Manages user authentication and sessions.
 Security Middleware: Implements security measures, such as preventing clickjacking or enforcing HTTPS.
 Logging Middleware: Records information about requests and responses for debugging and monitoring.
34
34. Example of Middleware in Django?
• Example Middleware Classes:
• django.middleware.security.SecurityMiddleware
• 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
• Configuration:
• Middleware classes are included in the MIDDLEWARE setting in the project's settings.py file to specify the
order of execution.
• Custom Middleware:
• Developers can create custom middleware classes by defining methods like process_request or
process_response to perform application-specific actions.
• Flexibility:
• Middleware provides flexibility to intercept and modify requests or responses globally, making it a powerful
tool for customizing the behavior of a Django application.
35
35. What is a session in Django?
Aspect Description
Purpose Sessions in Django are used to store and retrieve arbitrary data on a per-site-visitor basis.
Storage
Data is typically stored on the server side, and a session identifier is sent to the client via a
cookie.
State Management Maintains state and user-specific information across multiple requests and responses.
Session Middleware
Django uses session middleware to enable and manage sessions, handling the creation and
maintenance of data.
Session Engine Supports different session engines, with the default being the database-backed session engine.
Configuration
Session-related settings (engine, cookie settings, timeout) are configured in the settings.py
file.
Accessing Session Data
In Django views, developers can access session data using the request.session object, acting
like a dictionary.
Example
- Storing data: request.session['username'] = 'john_doe'<br> - Retrieving data: username =
request.session.get('username', 'Guest')
Security Considerations
Developers need to consider security aspects, such as protecting against session hijacking and
ensuring proper encryption for sensitive information. 36
36. What is the context in Django?
1. Definition: In Django, "context" refers to the data passed from a view to a template during the rendering process.
2. Nature: It is a dictionary-like object containing key-value pairs, where keys represent variable names, and values are associated
data.
3. Purpose: The context is used to provide dynamic data to templates, allowing them to generate content based on the information
provided by the view.
4. Example:
# views.py
from django.shortcuts import render
def my_view(request):
data = {'name': 'John', 'age': 25}
return render(request, 'my_template.html', context=data)
5. Template Usage: In templates, variables enclosed in double curly braces (e.g., {{ name }}) are placeholders that will be
replaced with corresponding values from the context during rendering.
6. Dynamic Content Generation: The context facilitates dynamic content generation in templates, allowing for personalized and
data-driven rendering.
37
37. What are Django exceptions?
Exception Class Description
django.core.exceptions.DoesNotExist
Indicates that a query for a single object with specific parameters
did not return any results.
django.core.exceptions.MultipleObjectsReturned
Indicates that a query for a single object with specific parameters
returned more than one result.
django.core.exceptions.ValidationError
Raised during data validation failures, commonly in forms or
model fields.
django.http.Http404 Signifies that the requested page or resource does not exist.
django.db.utils.IntegrityError
Indicates a violation of database integrity constraints, such as
unique constraints on fields.
django.core.exceptions.PermissionDenied
Raised when a user lacks the necessary permissions to perform a
specific action.
django.core.exceptions.SuspiciousOperation
Raised for suspicious or potentially dangerous operations that may
indicate a security issue.
1. Definition: Django exceptions are instances of classes that represent various errors or exceptional situations within a
Django application.
2. Purpose: They serve as a means of signaling and handling unexpected or erroneous conditions during the execution of
Django code.
38
38. Difference between Django OneToOneField and ForeignKey Field?
Aspect ForeignKey OneToOneField
Purpose Represents a many-to-one relationship Represents a one-to-one relationship
Usage models.ForeignKey(OtherModel) models.OneToOneField(OtherModel)
Example Books and Authors (multiple books to one author)
Person and UserProfile (one profile per
person)
Cardinality Many-to-one One-to-one
Multiplicity
Many instances on the "many" side can be associated
with one instance on the "one" side
Each instance on one side is associated with
exactly one instance on the other side
Example Illustration Author has multiple books, each book has one author Each person has exactly one user profile
39
39. Briefly explain Django Field Class and its types
Field Class Purpose and Description Example Usage
CharField Short to medium-length strings models.CharField(max_length=100)
IntegerField Integer values models.IntegerField()
FloatField Floating-point numbers models.FloatField()
BooleanField Boolean (True/False) values models.BooleanField()
DateField Date values models.DateField()
DateTimeField Date and time information models.DateTimeField()
TextField Long text strings models.TextField()
EmailField Email addresses models.EmailField()
ImageField Image files models.ImageField(upload_to='images/')
ForeignKey Many-to-one relationship between models models.ForeignKey(OtherModel,
on_delete=models.CASCADE)
OneToOneField One-to-one relationship between models models.OneToOneField(OtherModel,
on_delete=models.CASCADE)
ManyToManyField Many-to-many relationship between models models.ManyToManyField(OtherModel)
40
40. What is Jinja templating?
Feature Description Example
Variable
Substitution
Insert variables into templates using double curly
braces {{ variable_name }}.
<h1>Hello, {{ user_name }}!</h1>
Control Statements Support for if, for, and else statements. {% if user_authenticated %}...{% endif %}
Template
Inheritance
Create a base template and extend it in other templates
for code reusability.
Base Template (base.html):<br>{% block title
%}...{% endblock %}<br>Child Template
(page.html):<br>{% extends 'base.html' %}{%
block title %}...{% endblock %}
Filters Modify the output of variables or expressions using
filters applied with `
`.
Macros Define reusable blocks of content within templates. {% macro render_button(label) %}...{%
endmacro %}<br>Using the macro:
{{ render_button('Click me') }}
41
41. What is serialization in Django?
1. Definition: Serialization in Django refers to the process of converting complex data types into a format suitable for transport,
often JSON, to be sent as a response in web development.
2. Django Core Module: Django provides a built-in serialization framework through the django.core.serializers module. However, it's
more common to use Django REST framework for serialization tasks.
3. Django REST Framework (DRF): DRF is a powerful toolkit for building Web APIs in Django, and it includes a robust serialization
framework.
4. DRF Serializer: DRF serializers, similar to Django forms, enable the conversion of complex data types (e.g., model instances)
into JSON or other formats. They also handle validation of incoming data.
5. Example Serializer Code:
from rest_framework import serializers
class MyModelSerializer(serializers.ModelSerializer):
class Meta: model = MyModel
fields = '__all__'
6. Automatic Logic Generation: DRF serializers automatically generate serialization and deserialization logic based on the specified
model's fields. In the example, fields = '__all__' includes all model fields in the serialization.
7. RESTful APIs: Serialization is commonly used in building RESTful APIs where data needs to be exchanged between the server
and client in a standardized format, such as JSON.
8. Use Cases: Serialization is essential for sending data in API responses and processing incoming data from client requests.
42
42. What are generic views?
Generic View Purpose Example Usage
ListView Displays a list of objects retrieved from the
database.
python class MyModelListView(ListView): model = MyModel
template_name = 'myapp/my_model_list.html'
DetailView Displays details for a single object retrieved
from the database.
python class MyModelDetailView(DetailView): model = MyModel
template_name = 'myapp/my_model_detail.html'
CreateView Handles the creation of objects. python class MyModelCreateView(CreateView): model = MyModel
template_name = 'myapp/my_model_form.html' fields = ['field1',
'field2']
UpdateView Handles the updating of objects. python class MyModelUpdateView(UpdateView): model = MyModel
template_name = 'myapp/my_model_form.html' fields = ['field1',
'field2']
43
43. What is mixin?
Characteristic Description Example
Specific Functionality Mixins encapsulate a specific piece of
functionality or behavior.
python class JSONMixin: def to_json(self):
import json return json.dumps(self.__dict__)
No Standalone Use Mixins are not meant to be instantiated on
their own; they are designed to be combined
with other classes.
python class JSONPerson(Person, JSONMixin):
pass
Multiple Inheritance Mixins are often used in languages that
support multiple inheritance, allowing a class
to inherit from more than one class, including
one or more mixins.
python class JSONPerson(Person, JSONMixin):
pass
Enhancing Functionality Mixins provide a way to enhance or extend
the functionality of a class without the need
for deep inheritance hierarchies.
python class JSONPerson(Person, JSONMixin):
pass
44
44. List of Django's QuerySet API
Method Description
filter(**kwargs)
Returns a new QuerySet containing objects that match the given lookup
parameters.
exclude(**kwargs)
Returns a new QuerySet containing objects that do not match the given
lookup parameters.
get(**kwargs) Returns the unique object that matches the given lookup parameters.
chain(*iterables) Combines multiple QuerySets into a single QuerySet.
all() Returns a QuerySet that matches all objects in the database.
order_by(*fields) Orders the QuerySet by the specified fields.
exact, iexact, contains Various types of lookups on fields.
gt, lt, gte, lte, etc.
aggregate(**kwargs)
Performs aggregate functions (e.g., Sum, Avg, Count) on the values of a
QuerySet.
annotate(**kwargs) Adds extra fields to each object in the QuerySet.
union(*other_qs) Combines two or more QuerySets into a single QuerySet.
distinct() Returns a new QuerySet with duplicate objects removed.
values(*fields) Returns a QuerySet that returns dictionaries for each record.
values_list(*fields) Returns a QuerySet that returns tuples for each record.
select_related(*fields) Retrieves related objects in a single query.
prefetch_related(*lookups) Retrieves related objects efficiently in separate queries.
Paginator Allows for paginating QuerySets.
page(number) Returns a specific page of results.
45
Thanks
46
Feel free to connect with me:
Website: Md Naimur Rahman
LinkedIn: @mdnaimur
Twitter:@md_naimur100

Django Framework Interview Question and Answer partOne.pptx

  • 1.
    Django Framework InterviewQuestion And Answer Md Naimur Rahman
  • 2.
    1. What isDjango? 1. Framework: Django is a high-level web framework for building web applications in Python. 2. Architecture: It follows the Model-View-Template (MVT) pattern, similar to the Model-View-Controller (MVC) pattern. 3. Features:  ORM: Built-in Object-Relational Mapping for database interaction.  Admin Interface: Automatic admin interface for managing database records.  URL Routing: Flexible system for mapping URLs to views.  Template Engine: Built-in for defining and rendering HTML templates.  Security: Includes protections against common web vulnerabilities.  Authentication and Authorization: Robust tools for user management and permissions.  Middleware: Allows global processing of requests and responses.  Testing Support: Framework for easy development and execution of tests. 4. Philosophy: Django emphasizes rapid development, clean code, and follows the "Convention over Configuration" philosophy. 5. Usage: Widely used for projects of various sizes, from small to large-scale applications. 6. Principles: Promotes reusability, modularity, and adheres to the "Don't Repeat Yourself" (DRY) principle. 2
  • 3.
    2. Difference Betweena Project & App in Django? Aspect Django Project Django App Definition Represents the entire web application. A self-contained module handling a specific functionality. Functionality Contains overall settings, configurations, and multiple apps. Encapsulates specific aspects like models, views, and templates. Example A project named "MyBlog" for an entire blog website. Apps within "MyBlog" for functionalities like "Blog," "User Authentication," and "Comments." Hierarchy Top-level container tying together multiple apps. Modular component designed for a specific feature or functionality. Reusability Typically not reused in other projects. Intended to be reusable and can be plugged into different projects. Relationship One project can have multiple apps. An app is a component within a project. 3
  • 4.
    3. How dowe initialize a project and app in Django ? Step Command Description 1 pip install Django Install Django using pip. 2 django-admin startproject projectname Create a Django project. Replace "projectname" with your desired project name. 3 cd projectname Navigate to the project directory. 4 python manage.py startapp appname Create a Django app within the project. Replace "appname" with your desired app name. 5 Update INSTALLED_APPS in settings.py Add your app to the INSTALLED_APPS list in the project's settings. 6 python manage.py makemigrations Create database migration files. 7 python manage.py migrate Apply migrations to create database tables. 8 python manage.py runserver Start the development server at http://127.0.0.1:8000/. 9 python manage.py createsuperuser Create a superuser for the admin panel. 10 Admin Panel: http://127.0.0.1:8000/admin/ Access the admin panel using the superuser credentials. 4
  • 5.
    4. How dowe start our development server in Django? To start the development server in Django: 1. Open a terminal/command prompt in your project directory. 2. Run python manage.py runserver (or python3 for Python 3). 3. The default server address is http://127.0.0.1:8000/. 4. Access your Django app in a web browser. 5. For a custom host/port, use python manage.py runserver <host>:<port>.(python manage.py runserver 0.0.0.0:8080) 6. Development server is for testing, not for production; use Gunicorn/uWSGI with Nginx/Apache in production. 5
  • 6.
    5. What doesthe settings.py file do? The settings.py file in Django is a crucial configuration file for web applications. Key elements include: 1. Database Configuration: Specifies database details. 2. Debug Mode: Controls debug behavior. 3. Static and Media Files: Defines directories for static and media files. 4. Installed Apps: Lists active applications. 5. Middleware: Configures middleware components. 6. Template Configuration: Settings for template engines. 7. Timezone and Language: Sets default timezone and language. 8. Authentication and Authorization: Configures user authentication and authorization. 9. Security: Settings for enhancing application security. 10.Logging Configuration: Defines how the application logs messages. 11.Custom Settings: Allows developers to add project-specific configurations. 6
  • 7.
    6. What aremodels? What are views? What are templates? Component Definition Responsibilities Models Represent data structure, handle database operations. - Define structure of database tables. - Encapsulate logic for CRUD operations on the database. Views Handle presentation logic and user interface. - Process user requests. - Interact with models to retrieve data. - Return data to templates for rendering. Templates Responsible for presenting and rendering data. - Define structure of the final HTML or markup. - Use placeholders and control structures to insert data dynamically. 7
  • 8.
    7. What areurl patterns? In Django, URL patterns are typically configured in the urls.py file within each app of a project. Here's a breakdown:  URL Patterns: Fundamental in web development frameworks like Django.  Definition: Determine how incoming URLs are matched to views or functions.  Configuration: Defined in the urls.py file within each app.  Mapping to Views: Associate URL patterns with specific views or view functions.  Hierarchical Structure: Allows for organized and modular URL routing, supporting parameters.  Inclusion: Enables the composition of larger applications from smaller, reusable components. # In app/urls.py from django.urls import path from . import views urlpatterns = [ path('home/', views.home, name='home'), path('blog/<int:post_id>/', views.blog_detail, name='blog_detail'), ] 8
  • 9.
    9. What isthe Django Admin panel?  Django Admin Panel Overview:  Built-in feature of Django web framework.  Provides a graphical interface for managing application data.  Functionality:  Enables CRUD operations (Create, Read, Update, Delete) on models.  No need for custom views; automates data management tasks.  Key Features:  Highly customizable: developers can define display and edit preferences.  Incorporates robust security measures for authorized access.  Automatically generates user interface based on model definitions.  Integration with Models:  Seamless integration with Django models.  Leverages model information for form generation and data display.  Usage:  Register models with the admin site to enable admin functionality.  Accessible through a specified URL for efficient data management. 9
  • 10.
    9. What isMake migrations & migrate command? Django in Python, the terms "make migrations" and "migrate" are related to database management:  Make Migrations:  Generates migration files capturing changes to the database schema.  Examines Django models and creates migration files accordingly.  Command: python manage.py makemigrations.  Migrate:  Applies migration files to update the actual database schema.  Reads migration files and executes SQL statements or database-specific commands.  Ensures synchronization between code models and database structure.  Command: python manage.py migrate. 10
  • 11.
    10. What isFBV vs CBV in Django? Aspect Function-Based Views (FBV) Class-Based Views (CBV) Implementation Implemented as Python functions. Implemented as Python classes, with methods for different HTTP methods. Readability and Simplicity Generally simpler and more straightforward. May have a steeper learning curve but provides a more organized structure. Reusability Functions are less reusable unless explicitly designed as such. Classes and inheritance allow for better code reuse and organization. Organization and Structure May become less organized for complex views. Offers a more structured approach, making it easier to organize code. Flexibility and Extensibility May require additional decorators for functionality extension. Easily extendable through inheritance and mixins. Common Patterns Explicit handling of HTTP methods through conditionals. Django provides mixin classes and generic views for common patterns. # views.py from django.shortcuts import render def my_fbv(request): # View logic for handling the request return render(request, 'my_template.html') # views.py from django.views import View from django.shortcuts import render class MyCBV(View): def get(self, request): # View logic for handling GET requests return render(request, 'my_template.html') 11
  • 12.
    11. What isMEDIA_ROOT 1. Definition: MEDIA_ROOT is a setting in Django used to specify the absolute filesystem path to the directory where user-uploaded media files are stored. 2. Purpose: It facilitates the management of user-uploaded content, such as images and videos, by determining the location on the server's file system where these files are saved. 3. Configuration: MEDIA_ROOT is typically configured in the settings.py file of a Django project. It is used in conjunction with the MEDIA_URL setting, which defines the base URL for serving media files. 4. Example Configuration: 5. File Serving: It's important to configure the web server to handle requests for media files and point it to the specified MEDIA_ROOT directory when deploying a Django project in a production environment. 6. Usage: Once configured, Django uses MEDIA_ROOT to store user-uploaded media files, and MEDIA_URL to generate URLs for serving these files to users. # settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' 12
  • 13.
    12. What does"python manage.py collectstatic" do? 1. Purpose: collectstatic is a Django management command designed to gather static files (such as CSS, JavaScript, and images) from various apps within a Django project. 2. Collection Process: It collects static files from each app's static directory, taking into account potential naming conflicts. 3. Single Directory: The collected static files are combined into a single directory specified by the STATIC_ROOT setting in the project's settings.py file. 4. Deployment: This command is crucial during the deployment of a Django project, as it ensures that all necessary static files are organized in one location, making it easier to serve them efficiently. 5. Avoids Naming Conflicts: In case of identical filenames across apps, collectstatic appends unique identifiers to prevent naming conflicts. 6. Configuration Example: # settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') 13
  • 14.
    13. Serving staticfiles during production? 1. Configure STATIC_ROOT:  Set the STATIC_ROOT setting in the settings.py file to specify the absolute filesystem path where collected static files will be stored. 2. Run collectstatic Command:  Execute python manage.py collectstatic to gather static files from apps into the directory specified by STATIC_ROOT. 3. Web Server Configuration:  Configure your web server (e.g., Nginx, Apache) to serve static files directly.  For Nginx, use the alias directive.  For Apache, use the Alias directive. 4. CDN Usage:  Consider using a Content Delivery Network (CDN) to cache and distribute static files globally, improving delivery speed. 5. Compression:  Enable compression for static files to reduce bandwidth usage and enhance loading times. 6. Security Considerations:  Review and adjust security settings on the web server to restrict access and prevent unauthorized downloads of static files. 7. Separation of Static and Media Files:  Distinguish between static files (CSS, JavaScript) and media files (user uploads) using STATIC_URL and MEDIA_URL settings. 14
  • 15.
    14. What areCSRF Tokens? CSRF Tokens: 1. Purpose:  CSRF (Cross-Site Request Forgery) tokens are a security measure to protect web applications against malicious CSRF attacks. 2. Generation:  When a user authenticates, the server generates a unique and random CSRF token for the session. 3. Inclusion in Forms:  CSRF tokens are included in forms as hidden fields or in headers of HTTP requests. 4. Verification on Submission:  When a form is submitted, the server checks whether the CSRF token in the request matches the one associated with the user's session. 5. Protection Mechanism:  CSRF tokens prevent attackers from tricking users into making unintended and unauthorized requests by requiring the inclusion of a unique token in each form 15
  • 16.
    15. What isDRF?  DRF Overview:  Django Rest Framework (DRF) is a toolkit for building Web APIs in Django.  Key Features:  Serialization:  Converts complex data types into Python data for easy rendering into JSON.  Views:  Class-based views tailored for handling HTTP methods in API endpoints.  Authentication and Permissions:  Supports various authentication methods and permission controls.  ViewSets:  Classes combining logic for handling HTTP methods, promoting code reuse.  Routers:  Automatically wires up API views to URLs, reducing boilerplate code.  Browsable API:  Provides a browsable API for easy exploration and interaction.  Pagination:  Built-in support for efficiently paginating large data sets in API responses.  Usage:  Installed as a Django app, configured in the project for streamlined API development.  Benefits:  Widely used, well-documented, and offers flexibility in RESTful API development. 16
  • 17.
    16. What areDjango Signals? Django Signals:  Definition:  Django signals are a messaging mechanism facilitating communication between decoupled components in a Django application.  Components:  Sender:  Object triggering a signal.  Signal:  Messaging mechanism using django.dispatch.Signal.  Receiver:  Function responding to a signal.  Connecting:  Signals and receivers are connected using @receiver decorator or signal.connect() method.  Built-in Signals:  Django has built-in signals, like post_save, allowing customization and extension of default behavior.  Example:  Connect a function to the post_save signal of the User model to execute actions when a user is created or updated.  Benefits:  Promotes decoupling, modularization, and reusability in Django applications. 17
  • 18.
    17. What areModel Serializers? Model Serializers in Django Rest Framework (DRF):  Definition:  Specialized serializers in DRF for converting Django models to Python data types suitable for serialization.  Usage:  Inherit from serializers.ModelSerializer and specify the model and fields. Automatic field inference reduces explicit definitions.  Functionality:  Handles validation during deserialization and facilitates creating or updating model instances. 18
  • 19.
    18. Explain howa request is processed in Django? In Django, the request processing involves the following steps: 1. URL Dispatching:  Maps the requested URL to a view function using URL patterns. 2. View Function:  Processes the request, interacts with models, and returns an HTTP response. 3. Middleware Processing:  Global processing of requests and responses, before and after the view. 4. Template Rendering:  If applicable, generates dynamic HTML content using Django's template engine. 5. Response Object:  The view returns an instance of an HTTP response class. 6. Middleware Processing (post-view):  Additional processing or modifications to the response. 7. Sending the Response:  The processed response is sent back to the client, completing the request-response cycle. 19
  • 20.
    19. Why isDjango called a loosely coupled framework? Django is often referred to as a "loosely coupled" framework due to its design philosophy and architecture that promotes modularity, flexibility, and the separation of concerns. Here are some reasons why Django is considered loosely coupled: o Modular Components: o Django is comprised of modular components that can be used independently. o Developers can selectively utilize features like ORM, templating, and authentication without committing to the entire framework. o Reusable Apps: o Encourages the creation of reusable apps for specific functionalities. o Apps are self-contained, promoting code reusability and easy integration into different projects. o Separation of Concerns: o Follows the MVC (or MTV) architectural pattern, separating business logic (models), presentation (views/templates), and data handling. o Allows for organized and clear code structure. o Configurable Settings: o Django provides a settings module for project-specific configurations. o Developers can customize settings without tightly coupling their applications to the core framework. o Middleware Flexibility: o Middleware components enable global processing of requests and responses. o Developers can add or remove middleware based on project requirements, allowing for customization without tightly coupling to the framework. o Flexible Database Backbends: o Django's ORM offers an abstraction layer for database interactions. o Supports various database backbends, providing flexibility for developers to choose based on project needs. o Pluggable Authentication: o Offers a pluggable authentication system. o Developers can customize or replace authentication mechanisms, adapting them to specific application requirements. 20
  • 21.
    20. Explain theMigration in Django.  Purpose: Manage database schema changes over time.  Process:  Create an initial migration capturing current model state.  Use makemigrations to generate migration files based on model changes.  Apply migrations with migrate to update the database schema.  Migration Files: Python scripts in the migrations directory of each app.  Commands:  makemigrations: Generates migration files.  migrate: Applies pending migrations to the database.  Rollback: Use migrate with a specific migration name or python manage.py migrate app_name zero to revert migrations.  History: Migrations are recorded in the django_migrations table for tracking 21
  • 22.
    21. What isDjango ORM?  Object-Relational Mapping (ORM):  Django ORM is a component of the Django web framework.  It facilitates interaction with relational databases using an object- oriented approach.  Models:  Models are defined as Python classes in Django ORM.  Each model class corresponds to a database table, and class attributes represent table fields.  Database Migration:  Django provides a migration system for evolving database schemas.  Developers can make changes to models, and Django handles the creation and updating of database tables.  Querysets:  Django ORM uses Querysets, which are Pythonic APIs for database queries.  Allows filtering, ordering, and aggregating data in a way that resembles SQL but is written in Python.  Automatic Admin Interface:  Django automatically generates a web-based admin interface for models.  This interface simplifies data management during development and testing.  Productivity and Maintainability:  Django ORM abstracts the complexities of database interactions, allowing developers to focus on application logic.  Enhances productivity by reducing the need for manual SQL queries and providing a higher-level interface. 22
  • 23.
    22. Difference betweenselect_related and prefetch_related in Django? Feature select_related prefetch_related Use Case ForeignKey and OneToOneField relationships Many-to-many and reverse ForeignKey/OneToOneField relationships Query Strategy Performs a SQL join, includes related fields in the SELECT statement Does separate lookups for each relationship, fetches related objects, and does mapping in Python Efficiency More efficient for ForeignKey and OneToOneField relationships More efficient for many-to-many and reverse ForeignKey/OneToOneField relationships Number of Queries Reduces the number of queries by fetching related objects in a single query Reduces the number of queries by fetching all related objects in a single query Example python Book.objects.select_related('author').get(id=1).author python Author.objects.prefetch_related('book_set' ).get(id=1).book_set.all() 23
  • 24.
    23. Difference betweenEmp.object.filter(), Emp.object.get() and Emp.objects.all() in Django Queryset? Feature Emp.objects.filter() Emp.objects.get() Emp.objects.all() Purpose Retrieve a set of objects matching criteria Retrieve a single object based on specific criteria Retrieve all objects of a particular model Returned Type QuerySet (can contain multiple objects) Single model instance QuerySet (contains all instances of the model) Exception Handling Does not raise exceptions if no match is found Raises DoesNotExist if no match is found, Raises MultipleObjectsReturned if more than one match is found Does not raise exceptions Example Emp.objects.filter(job_title='Develope r') Emp.objects.get(id=1) Emp.objects.all() 24
  • 25.
    24. Which CompaniesUse Django? 1.Instagram: One of the largest social media platforms for sharing photos and videos. 2.Pinterest: A popular visual discovery and bookmarking platform. 3.Disqus: A platform for web comments and discussions. 4.Spotify: A leading music streaming service. 5.Dropbox: A cloud storage and collaboration platform. 6.Mozilla: The organization behind the Firefox web browser. 7.NASA: The National Aeronautics and Space Administration uses Django for some of its web applications. 8.Eventbrite: An online event management and ticketing platform. 9.Bitbucket: A Git repository hosting service. 10.The Washington Post: A major American newspaper. 11.Reddit: Parts of Reddit's infrastructure use Django. 25
  • 26.
    25. What isthe difference between Flask, Pyramid, and Django? Feature Flask Pyramid Django Philosophy Micro framework, simplicity, flexibility Modular, flexible, "use what you need" approach Batteries-included, rapid development, convention over configuration Complexity Lightweight and minimalistic Moderate complexity, scalable for various projects High-level, comprehensive, includes many built-in features Architecture Pattern No strict adherence, flexible Flexible, supports different architectural patterns MTV (Model-Template-View) ORM Not included by default, can be added Not included by default, can be integrated with various ORMs Django ORM included, tightly integrated Template Engine Jinja2 Mako, Chameleon, Jinja2 (choice of templating engines) Django Template Language (DTL) Authentication Not built-in, can be added through extensions Built-in authentication system Built-in authentication system, user management Admin Interface No built-in admin interface No built-in admin interface (can be added) Powerful built-in admin interface Flexibility Highly flexible, more manual configuration Flexible, modular, choose components as needed More opinionated, less flexibility, more conventions Community Support Active community, large number of extensions Active community, modular design encourages contributions Large and active community, extensive documentation Use Cases Small to medium-sized projects, APIs Wide range of projects, scalable Medium to large-sized projects, content- heavy websites, applications with built-in admin interfaces 26
  • 27.
    26.What are theadvantages/disadvantages of using Django? Advantages of Django Disadvantages of Django High-level Abstraction Learning Curve Rapid Development Monolithic Structure ORM (Object-Relational Mapping) Overhead Admin Interface Template System Security Features Opinionated Versatility API Complexity Community and Documentation Scalability 27
  • 28.
    27. What IsThe Difference Between Authentication And Authorization Aspect Authentication Authorization Focus Verifying the identity of a user or system. Determining access rights based on the authenticated identity. Purpose Ensures the user is who they claim to be. Regulates access to resources based on user permissions. Verification vs. Permission Involves verifying identity credentials (e.g., username and password). Involves checking permissions associated with an authenticated identity. Example Verifying login credentials (username and password). Allowing access to specific pages or actions based on user roles. Process Flow The initial step in the access control process. Follows authentication and determines access levels. 28
  • 29.
    28. What IsDjango.Shortcuts.Render Function? 1. Purpose: django.shortcuts.render simplifies the rendering of HTML templates within Django views. 2. Parameters:  request: Represents the HTTP request object.  template_name: Specifies the name or path of the template file to be rendered.  context: A dictionary containing data to be passed to the template for rendering. 3. Usage Example: from django.shortcuts import render def my_view(request): data = {'key': 'value'} return render(request, 'my_template.html', context=data) 4. Convenience: Provides a convenient way to generate HTML responses by handling the rendering process and context data. 5. Code Organization: Promotes separation of concerns by keeping view logic separate from template rendering in Django applications. 29
  • 30.
    29. What AimQ Objects In Django ORM? In Django ORM, a Q object is a tool that helps make database queries more flexible and dynamic. Here's a simpler explanation: Complex Queries: Purpose: Q objects let you create queries with multiple conditions, combining them using AND, OR, and NOT. Example: from django.db.models import Q # Find books published after 2000 or authored by a specific author Book.objects.filter(Q(pub_date__gt='2000- 01-01') | Q(author='John Doe')) Logical Operators: Purpose: Q objects support logical AND, OR, and NOT, allowing you to build more intricate query conditions. Example: from django.db.models import Q # Find books published after 2000 and authored by a specific author Book.objects.filter(Q(pub_date__gt='2000- 01-01') & Q(author='John Doe')) Dynamic Query Building: Purpose: Q objects are handy for creating queries based on changing conditions, like user input. Example: from django.db.models import Q # Dynamic query based on author and publication date def dynamic_book_query(author, pub_date): query = Q() if author: query &= Q(author=author) if pub_date: query &= Q(pub_date__gt=pub_date) return Book.objects.filter(query) Combining Queries: Purpose: Q objects can be combined for more complex queries by nesting or using logical operators. Example: from django.db.models import Q # Find books published after 2000 and authored by John Doe or Jane Doe Book.objects.filter(Q(pub_date__gt='2 000-01-01') & (Q(author='John Doe') | Q(author='Jane Doe'))) Readability and Maintainability: Purpose: Q objects make queries easier to read, especially with multiple conditions, improving code maintainability. Example: from django.db.models import Q # Query with multiple conditions using Q objects Book.objects.filter(Q(pub_date__gt='2 000-01-01') | (Q(author='John Doe) 30
  • 31.
    30. What IsThe Significance Of The Manage.Py File In Django? Functionality Description Example Command Line Interface Provides a command-line interface for Django-related tasks. python manage.py runserver Database Migrations Manages database migrations for applying, unapplying, and inspecting changes to the database schema over time. python manage.py migrate Create Superuser Allows the creation of a superuser account for accessing the Django admin interface. python manage.py createsuperuser Django Shell Launches an interactive Python shell with the Django environment pre-loaded. python manage.py shell Testing Runs tests for the Django project to ensure code correctness. python manage.py test Custom Commands Supports the creation and execution of custom management commands. python manage.py my_custom_command Static Files Collection Collects static files from apps into a single directory during deployment. python manage.py collectstatic Project Configuration Reads the project's settings and configuration, serving as the starting point for many Django operations. python manage.py diffsettings 31
  • 32.
    31. What IsThe Use Of The Include Function In The Urls.Py File 1. Inclusion of URL Patterns: include function is used in Django's urls.py to include URL patterns from other files or apps into the main project. 2. Modularization: It promotes modularization by allowing the separation of URL patterns into distinct files, enhancing code organization. 3. Organized Code Structure: By using include, the main urls.py file remains cleaner and more focused, improving readability and maintainability. 4. Reuse of Patterns: Enables the reuse of URL patterns across different components of the Django project, fostering code efficiency. 5. Example Usage: # project/urls.py from django.urls import path, include from myapp import views urlpatterns = [ path('admin/', admin.site.urls), path('myapp/', include('myapp.urls')), # other URL patterns for the main project ] # myapp/urls.py from django.urls import path from . import views urlpatterns = [ path('some-view/', views.some_view, name='some_view'), # other URL patterns for the 'myapp' app ] 32
  • 33.
    32. What Does{% Include %} Do In Django? 1. Inclusion of Template Content: {% include %} is a Django template tag used to embed the content of another template within the current template. 2. Modularization: Enables modularization of template code by allowing the reuse of common components in different templates. 3. Reduction of Redundancy: Reduces redundancy by centralizing common content in separate templates and including them where needed. 4. Example Usage: Html <!-- main_template.html --> <div> <h1>Main Content</h1> </div> <div> {% include 'included_template.html' %} </div> html <!-- included_template.html --> <p>This content is included in the main template.</p> 5. Enhanced Maintainability: Promotes maintainability by allowing changes to be made in a single included template, reflecting updates across multiple locations where it is included. Top of Form 33
  • 34.
    33. What isa Middleware in Django? • Definition:  Middleware in Django is a mechanism to process requests and responses globally in a Django web application. • Functionality:  Middleware classes execute before or after the view processes the request, allowing for global actions on incoming requests or outgoing responses. • Chain of Classes:  Middleware functions as a chain of classes, each designed for specific tasks like authentication, security, logging, or request/response modification. • Order of Execution:  Middleware classes are executed in a specific order as defined in the MIDDLEWARE setting in the project's settings.py file. • Common Use Cases:  Authentication Middleware: Manages user authentication and sessions.  Security Middleware: Implements security measures, such as preventing clickjacking or enforcing HTTPS.  Logging Middleware: Records information about requests and responses for debugging and monitoring. 34
  • 35.
    34. Example ofMiddleware in Django? • Example Middleware Classes: • django.middleware.security.SecurityMiddleware • 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 • Configuration: • Middleware classes are included in the MIDDLEWARE setting in the project's settings.py file to specify the order of execution. • Custom Middleware: • Developers can create custom middleware classes by defining methods like process_request or process_response to perform application-specific actions. • Flexibility: • Middleware provides flexibility to intercept and modify requests or responses globally, making it a powerful tool for customizing the behavior of a Django application. 35
  • 36.
    35. What isa session in Django? Aspect Description Purpose Sessions in Django are used to store and retrieve arbitrary data on a per-site-visitor basis. Storage Data is typically stored on the server side, and a session identifier is sent to the client via a cookie. State Management Maintains state and user-specific information across multiple requests and responses. Session Middleware Django uses session middleware to enable and manage sessions, handling the creation and maintenance of data. Session Engine Supports different session engines, with the default being the database-backed session engine. Configuration Session-related settings (engine, cookie settings, timeout) are configured in the settings.py file. Accessing Session Data In Django views, developers can access session data using the request.session object, acting like a dictionary. Example - Storing data: request.session['username'] = 'john_doe'<br> - Retrieving data: username = request.session.get('username', 'Guest') Security Considerations Developers need to consider security aspects, such as protecting against session hijacking and ensuring proper encryption for sensitive information. 36
  • 37.
    36. What isthe context in Django? 1. Definition: In Django, "context" refers to the data passed from a view to a template during the rendering process. 2. Nature: It is a dictionary-like object containing key-value pairs, where keys represent variable names, and values are associated data. 3. Purpose: The context is used to provide dynamic data to templates, allowing them to generate content based on the information provided by the view. 4. Example: # views.py from django.shortcuts import render def my_view(request): data = {'name': 'John', 'age': 25} return render(request, 'my_template.html', context=data) 5. Template Usage: In templates, variables enclosed in double curly braces (e.g., {{ name }}) are placeholders that will be replaced with corresponding values from the context during rendering. 6. Dynamic Content Generation: The context facilitates dynamic content generation in templates, allowing for personalized and data-driven rendering. 37
  • 38.
    37. What areDjango exceptions? Exception Class Description django.core.exceptions.DoesNotExist Indicates that a query for a single object with specific parameters did not return any results. django.core.exceptions.MultipleObjectsReturned Indicates that a query for a single object with specific parameters returned more than one result. django.core.exceptions.ValidationError Raised during data validation failures, commonly in forms or model fields. django.http.Http404 Signifies that the requested page or resource does not exist. django.db.utils.IntegrityError Indicates a violation of database integrity constraints, such as unique constraints on fields. django.core.exceptions.PermissionDenied Raised when a user lacks the necessary permissions to perform a specific action. django.core.exceptions.SuspiciousOperation Raised for suspicious or potentially dangerous operations that may indicate a security issue. 1. Definition: Django exceptions are instances of classes that represent various errors or exceptional situations within a Django application. 2. Purpose: They serve as a means of signaling and handling unexpected or erroneous conditions during the execution of Django code. 38
  • 39.
    38. Difference betweenDjango OneToOneField and ForeignKey Field? Aspect ForeignKey OneToOneField Purpose Represents a many-to-one relationship Represents a one-to-one relationship Usage models.ForeignKey(OtherModel) models.OneToOneField(OtherModel) Example Books and Authors (multiple books to one author) Person and UserProfile (one profile per person) Cardinality Many-to-one One-to-one Multiplicity Many instances on the "many" side can be associated with one instance on the "one" side Each instance on one side is associated with exactly one instance on the other side Example Illustration Author has multiple books, each book has one author Each person has exactly one user profile 39
  • 40.
    39. Briefly explainDjango Field Class and its types Field Class Purpose and Description Example Usage CharField Short to medium-length strings models.CharField(max_length=100) IntegerField Integer values models.IntegerField() FloatField Floating-point numbers models.FloatField() BooleanField Boolean (True/False) values models.BooleanField() DateField Date values models.DateField() DateTimeField Date and time information models.DateTimeField() TextField Long text strings models.TextField() EmailField Email addresses models.EmailField() ImageField Image files models.ImageField(upload_to='images/') ForeignKey Many-to-one relationship between models models.ForeignKey(OtherModel, on_delete=models.CASCADE) OneToOneField One-to-one relationship between models models.OneToOneField(OtherModel, on_delete=models.CASCADE) ManyToManyField Many-to-many relationship between models models.ManyToManyField(OtherModel) 40
  • 41.
    40. What isJinja templating? Feature Description Example Variable Substitution Insert variables into templates using double curly braces {{ variable_name }}. <h1>Hello, {{ user_name }}!</h1> Control Statements Support for if, for, and else statements. {% if user_authenticated %}...{% endif %} Template Inheritance Create a base template and extend it in other templates for code reusability. Base Template (base.html):<br>{% block title %}...{% endblock %}<br>Child Template (page.html):<br>{% extends 'base.html' %}{% block title %}...{% endblock %} Filters Modify the output of variables or expressions using filters applied with ` `. Macros Define reusable blocks of content within templates. {% macro render_button(label) %}...{% endmacro %}<br>Using the macro: {{ render_button('Click me') }} 41
  • 42.
    41. What isserialization in Django? 1. Definition: Serialization in Django refers to the process of converting complex data types into a format suitable for transport, often JSON, to be sent as a response in web development. 2. Django Core Module: Django provides a built-in serialization framework through the django.core.serializers module. However, it's more common to use Django REST framework for serialization tasks. 3. Django REST Framework (DRF): DRF is a powerful toolkit for building Web APIs in Django, and it includes a robust serialization framework. 4. DRF Serializer: DRF serializers, similar to Django forms, enable the conversion of complex data types (e.g., model instances) into JSON or other formats. They also handle validation of incoming data. 5. Example Serializer Code: from rest_framework import serializers class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' 6. Automatic Logic Generation: DRF serializers automatically generate serialization and deserialization logic based on the specified model's fields. In the example, fields = '__all__' includes all model fields in the serialization. 7. RESTful APIs: Serialization is commonly used in building RESTful APIs where data needs to be exchanged between the server and client in a standardized format, such as JSON. 8. Use Cases: Serialization is essential for sending data in API responses and processing incoming data from client requests. 42
  • 43.
    42. What aregeneric views? Generic View Purpose Example Usage ListView Displays a list of objects retrieved from the database. python class MyModelListView(ListView): model = MyModel template_name = 'myapp/my_model_list.html' DetailView Displays details for a single object retrieved from the database. python class MyModelDetailView(DetailView): model = MyModel template_name = 'myapp/my_model_detail.html' CreateView Handles the creation of objects. python class MyModelCreateView(CreateView): model = MyModel template_name = 'myapp/my_model_form.html' fields = ['field1', 'field2'] UpdateView Handles the updating of objects. python class MyModelUpdateView(UpdateView): model = MyModel template_name = 'myapp/my_model_form.html' fields = ['field1', 'field2'] 43
  • 44.
    43. What ismixin? Characteristic Description Example Specific Functionality Mixins encapsulate a specific piece of functionality or behavior. python class JSONMixin: def to_json(self): import json return json.dumps(self.__dict__) No Standalone Use Mixins are not meant to be instantiated on their own; they are designed to be combined with other classes. python class JSONPerson(Person, JSONMixin): pass Multiple Inheritance Mixins are often used in languages that support multiple inheritance, allowing a class to inherit from more than one class, including one or more mixins. python class JSONPerson(Person, JSONMixin): pass Enhancing Functionality Mixins provide a way to enhance or extend the functionality of a class without the need for deep inheritance hierarchies. python class JSONPerson(Person, JSONMixin): pass 44
  • 45.
    44. List ofDjango's QuerySet API Method Description filter(**kwargs) Returns a new QuerySet containing objects that match the given lookup parameters. exclude(**kwargs) Returns a new QuerySet containing objects that do not match the given lookup parameters. get(**kwargs) Returns the unique object that matches the given lookup parameters. chain(*iterables) Combines multiple QuerySets into a single QuerySet. all() Returns a QuerySet that matches all objects in the database. order_by(*fields) Orders the QuerySet by the specified fields. exact, iexact, contains Various types of lookups on fields. gt, lt, gte, lte, etc. aggregate(**kwargs) Performs aggregate functions (e.g., Sum, Avg, Count) on the values of a QuerySet. annotate(**kwargs) Adds extra fields to each object in the QuerySet. union(*other_qs) Combines two or more QuerySets into a single QuerySet. distinct() Returns a new QuerySet with duplicate objects removed. values(*fields) Returns a QuerySet that returns dictionaries for each record. values_list(*fields) Returns a QuerySet that returns tuples for each record. select_related(*fields) Retrieves related objects in a single query. prefetch_related(*lookups) Retrieves related objects efficiently in separate queries. Paginator Allows for paginating QuerySets. page(number) Returns a specific page of results. 45
  • 46.
    Thanks 46 Feel free toconnect with me: Website: Md Naimur Rahman LinkedIn: @mdnaimur Twitter:@md_naimur100