DJANGO PYTHON
Logical/Essay Questions with Answers
Bachelor of Science (BSc) Exam Preparation
QUESTIONS
Question 1: Explain the MTV (Model-Template-View) architecture of Django and how it
differs from the traditional MVC architecture.
Question 2: What is the Django ORM and what are its advantages over writing raw SQL
queries?
Question 3: Describe the process of creating and applying migrations in Django. Why are
migrations important?
Question 4: Explain Class-Based Views (CBVs) and their advantages over Function-Based
Views (FBVs).
Question 5: What is Django's template inheritance system and how does it promote code
reusability?
Question 6: Explain the request-response cycle in Django and the role of middleware.
Question 7: How does Django's authentication system work and what are the key
components?
Question 8: Describe Django Forms and explain the difference between Form and
ModelForm.
Question 9: What is the purpose of the Django Admin interface and how can you
customize it?
Question 10: Explain URL routing in Django and how URL parameters are captured and
used.
Question 11: Describe the purpose and usage of Django signals.
Question 12: What are Django querysets and how are they lazy evaluated?
Question 13: Explain static files management in Django and how to serve them in
production.
Question 14: What are Django model relationships and how do you implement them?
Question 15: Describe security features in Django and why they are important.
ANSWERS
Answer 1:
The MTV architecture is Django's implementation of the Model-View-Controller pattern. In MTV:
Model represents the data layer and database logic, Template represents the presentation layer
(HTML/CSS), and View contains the business logic. Unlike traditional MVC where the View is the
presentation layer, in Django the View is the controller. This naming convention can be confusing
but helps maintain separation of concerns. Models define database structure, Templates handle
display, and Views process requests and return responses.
Answer 2:
The Django Object-Relational Mapping (ORM) is a system for interacting with databases using
Python objects instead of SQL. Advantages include: 1) Database agnosticism - write once, work
with multiple databases, 2) Protection against SQL injection attacks, 3) More readable and
maintainable Python code, 4) Less boilerplate code, 5) Automatic query optimization, 6) Type
safety through Python. For example, User.objects.filter(age__gte=18) is more Pythonic than
SELECT * FROM users WHERE age >= 18.
Answer 3:
Migrations track database schema changes over time. The process involves: 1) Make changes to
models.py, 2) Run 'python manage.py makemigrations' to create migration files, 3) Review
generated migration files, 4) Run 'python manage.py migrate' to apply changes. Migrations are
important because they: provide version control for database schema, enable rollback to previous
versions, help teams collaborate on database changes, track database evolution, and allow
testing of schema changes.
Answer 4:
Class-Based Views are views implemented as Python classes instead of functions. Advantages:
1) Code reusability through inheritance, 2) DRY principle - generic views reduce code repetition,
3) Better organization with mixins, 4) Easier to extend functionality, 5) Clearer code structure. For
example, ListView automatically handles pagination, filtering, and context passing. FBVs are
simpler for basic views but CBVs are better for complex, reusable logic. Django provides generic
CBVs like ListView, DetailView, CreateView, UpdateView, DeleteView.
Answer 5:
Django templates support inheritance through extends and block tags. A base template defines
the overall structure with named blocks, and child templates extend the base, overriding only
necessary blocks. This promotes reusability by: 1) Eliminating repeated HTML structure, 2)
Maintaining consistent layout across pages, 3) Allowing changes in one place, 4) Creating
modular, maintainable templates. Example: base.html defines headers and footers, while
user.html extends base.html and only defines its content block.
Answer 6:
The request-response cycle: 1) Browser sends HTTP request, 2) Django receives it and passes
through middleware, 3) URL routing matches request to view, 4) View processes request and
queries database, 5) Response passes back through middleware, 6) Browser receives response.
Middleware acts as hooks that intercept requests and responses. Common middleware includes
SecurityMiddleware (adds security headers), SessionMiddleware (manages sessions),
AuthenticationMiddleware (authenticates users), CsrfViewMiddleware (prevents CSRF attacks).
Custom middleware can be created for specific needs.
Answer 7:
Django provides a built-in authentication system with key components: 1) User model storing
username, password, email, 2) Authentication backend for credentials verification, 3) Session
framework for maintaining login state, 4) Permission system for access control. Usage:
authenticate() verifies credentials, login() creates session, @login_required decorator restricts
access. Django hashes passwords using PBKDF2 by default. User permissions and groups
enable fine-grained access control. Decorators like @permission_required and
@user_passes_test provide authorization.
Answer 8:
Django Forms handle HTML form generation, validation, and processing. Form is a generic form
class, while ModelForm automatically generates form fields from model. Advantages of
ModelForm: 1) DRY - no field duplication, 2) Automatic validation based on model fields, 3) Easy
saving with form.save(), 4) Sync with model changes. Forms are used for validation and
rendering, containing field definitions, clean methods for validation, and widgets for HTML
rendering. ModelForm is preferred when directly creating/updating model instances.
Answer 9:
The Django Admin interface is an automatically generated admin site for model CRUD operations.
Register models using admin.site.register(). Customization includes: 1) ModelAdmin class with
list_display, search_fields, list_filter, 2) Custom actions for bulk operations, 3) Fieldsets for
organizing form fields, 4) Readonly fields, 5) Custom inlines for related objects, 6) Custom admin
methods. It saves development time by eliminating need for manual admin views, provides
security through permissions, and offers a professional interface for content management.
Answer 10:
URL routing matches HTTP requests to view functions using path patterns. In urls.py, path()
function maps URL patterns to views. URL parameters are captured using angle brackets with
type converters: for integers, for strings, for slugs. Parameters are passed to view as keyword
arguments. For example, path('users//', views.user_detail) passes id to user_detail view. Include()
allows nested URL configurations for modular routing. URL names enable reverse URL lookup
using reverse() function.
Answer 11:
Django signals are a way to notify multiple receivers that an event has occurred. Common signals:
pre_save, post_save, pre_delete, post_delete. They enable decoupled applications where
receivers can react to model changes without tight coupling. Usage: define signal handler,
connect it using @receiver or connect() method. Example: create user profile when User model is
saved. Signals allow executing code automatically when models change, useful for logging,
notifications, cache invalidation, and maintaining data consistency.
Answer 12:
Querysets are database queries that haven't been evaluated yet. They support method chaining
for building complex queries. Lazy evaluation means querysets don't hit the database until
explicitly evaluated. Evaluation triggers: iteration, slicing, repr(), len(), list(), bool(), exists(). This
allows: 1) Complex query building without database hits, 2) Filter combination before execution, 3)
Better performance. For example, queryset = User.objects.filter(age__gte=18).filter(active=True)
doesn't hit database until you iterate or call list().
Answer 13:
Static files are CSS, JavaScript, images that don't change. Configure STATIC_URL in settings.py.
Use {% static %} template tag to reference files. Development: Django serves automatically.
Production: run 'python manage.py collectstatic' to gather files to STATIC_ROOT, then serve from
web server (nginx/Apache). Benefits: separation of content, caching, compression, CDN
integration. Best practices: version files for caching, use minified files, use static file storage
backend for cloud storage.
Answer 14:
Django supports three relationship types: 1) ForeignKey - one-to-many relationship creating
reference to another model, 2) ManyToManyField - many-to-many relationship through junction
table, 3) OneToOneField - one-to-one relationship. Example: Author-Book uses ForeignKey,
Student-Course uses ManyToManyField. Access related objects using attribute access
(book.author) or reverse relations (author.book_set). Relationships enable querying across tables,
automatic referential integrity, and cascade deletes.
Answer 15:
Django includes multiple security features: 1) CSRF tokens prevent cross-site request forgery, 2)
SQL injection protection through ORM, 3) Password hashing with PBKDF2, 4) XSS protection
through template auto-escaping, 5) Security middleware adds headers, 6) Secure cookie settings
(HttpOnly, Secure flags), 7) Content Security Policy support. These features protect against
common web vulnerabilities. HTTPS enforcement, input validation, output encoding, and regular
updates are crucial. SECURE_HSTS_SECONDS setting enforces HTTPS, X-Frame-Options
prevents clickjacking.