Django Interview Questions
35 questions with detailed answers
Question:
What is Django and what are its key features?
Answer:
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design.
Key features include:
• MVT architecture
• ORM (Object-Relational Mapping)
• Admin interface
• URL routing
• Template engine
• Form handling
• Security features (CSRF, XSS protection)
• Internationalization support
• Scalability
Question:
Explain the MVT (Model-View-Template) architecture in Django.
Answer:
MVT is Django's architectural pattern:
• Model - Defines data structure and database schema, handles data logic
• View - Contains business logic, processes requests and returns responses
• Template - Handles presentation layer, defines how data is displayed to users
Unlike MVC, Django's "View" acts as the controller, and "Template" is the view.
Question:
How do you create a new Django project and app?
Answer:
Steps to create Django project and app:
1. Create project: django-admin startproject myproject
2. Navigate to project: cd myproject
3. Create app: python manage.py startapp myapp
4. Add app to INSTALLED_APPS in settings.py
5. Run migrations: python manage.py migrate
6. Start server: python manage.py runserver
Question:
What is Django ORM and how does it work?
Answer:
Django ORM (Object-Relational Mapping) is a technique that lets you query and manipulate data using Python objects instead of SQL.
It provides:
• Database abstraction
• Model classes that represent database tables
• QuerySet API for database operations
• Automatic SQL generation
• Database migrations
• Support for multiple database backends
Question:
Explain Django models and their field types.
Answer:
Django models are Python classes that define database table structure.
Common field types:
• CharField - text fields
• IntegerField - integers
• DateTimeField - date/time
• BooleanField - true/false
• ForeignKey - relationships
• ManyToManyField - many-to-many relationships
• EmailField - email validation
• URLField - URL validation
• TextField - large text
• DecimalField - decimal numbers
Question:
What are Django migrations and how do they work?
Answer:
Migrations are Django's way of propagating model changes to database schema.
Process:
1. Make model changes
2. Run makemigrations to create migration files
3. Run migrate to apply changes to database
Migration files contain operations like:
• CreateModel
• AddField
• RemoveField
Benefits:
• Version control for database schema
• Team collaboration
• Rollback capability
Question:
Explain Django URL routing and how to configure URLs.
Answer:
Django URL routing maps URLs to views using URLconf.
Configuration:
1. Create urls.py in app
2. Define urlpatterns list with path() or re_path()
3. Include app URLs in project urls.py
Example: path('blog/', views.blog_view, name='blog')
Supports:
• Named URLs
• URL parameters
• Regular expressions
• Namespaces
• URL reversing with reverse() or {% url %} tag
Question:
What are Django views and their types?
Answer:
Views handle HTTP requests and return responses.
Types:
• Function-based views (FBV) - Simple functions that take request and return response
• Class-based views (CBV) - Classes that provide more structure and reusability
• Generic views - Pre-built views for common patterns (ListView, DetailView, CreateView, UpdateView, DeleteView)
CBVs offer better code organization and inheritance.
Question:
Explain Django templates and template inheritance.
Answer:
Django templates separate presentation from logic using HTML with template tags.
Features:
• Variables {{ variable }}
• Tags {% tag %}
• Filters {{ variable|filter }}
• Comments {# comment #}
Template inheritance:
• Base template defines structure with {% block %} tags
• Child templates extend base with {% extends %} and override blocks
Benefits:
• Code reusability
• Consistent layout
• Easy maintenance
Question:
What is Django admin interface and how to customize it?
Answer:
Django admin is an automatic admin interface for Django models.
Setup:
• Create superuser with createsuperuser
• Register models in admin.py
Customization:
• ModelAdmin classes
• list_display, list_filter, search_fields
• fieldsets, inlines
• custom actions, permissions
Benefits:
• Rapid content management
• User-friendly interface
• Extensible and customizable
Question:
Explain Django forms and form validation.
Answer:
Django forms handle HTML form generation and validation.
Types:
• Form (basic)
• ModelForm (based on models)
Features:
• Automatic HTML generation
• CSRF protection
• Field validation
• Custom validators
• Error handling
Validation process:
• Field validation
• Form validation (clean methods)
• Model validation
Example:
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
Question:
What is Django's request-response cycle?
Answer:
Django's request-response cycle:\n\n1. **URL Resolution** - Django matches the requested URL against URL patterns\n2. **Middleware Processing** - Request passes through middleware layers\n3. **View Execution** - Matched view function/class is called\n4. **Template Rendering** - View renders template with context data\n5. **Response Creation** - HttpResponse object is created\n6. **Middleware Processing** - Response passes back through middleware\n7. **Response Delivery** - Final response sent to client\n\nMiddleware can modify requests/responses at each step.
Question:
Explain Django's static files handling and configuration.
Answer:
Django static files handling:\n\n**Settings:**\n• STATIC_URL - URL prefix for static files\n• STATIC_ROOT - Directory for collected static files\n• STATICFILES_DIRS - Additional directories to search\n• STATICFILES_FINDERS - Classes to find static files\n\n**Commands:**\n• python manage.py collectstatic - Collect all static files\n• python manage.py findstatic - Find specific static file\n\n**In templates:**\n• {% load static %}\n• {% static 'css/style.css' %}\n\n**Production:**\n• Use web server (Nginx/Apache) to serve static files\n• CDN integration for better performance
Question:
What are Django model relationships and how to implement them?
Answer:
Django model relationships:\n\n**One-to-Many (ForeignKey):**\n```python\nclass Author(models.Model):\n name = models.CharField(max_length=100)\n\nclass Book(models.Model):\n author = models.ForeignKey(Author, on_delete=models.CASCADE)\n```\n\n**Many-to-Many:**\n```python\nclass Book(models.Model):\n authors = models.ManyToManyField(Author)\n```\n\n**One-to-One:**\n```python\nclass Profile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n```\n\n**on_delete options:**\n• CASCADE - Delete related objects\n• PROTECT - Prevent deletion\n• SET_NULL - Set to NULL\n• SET_DEFAULT - Set to default value
Question:
How do you handle file uploads in Django?
Answer:
Django file upload handling:\n\n**Model Field:**\n```python\nclass Document(models.Model):\n file = models.FileField(upload_to='documents/')\n image = models.ImageField(upload_to='images/')\n```\n\n**Form Handling:**\n```python\nclass UploadForm(forms.Form):\n file = forms.FileField()\n \n# In view\nif form.is_valid():\n uploaded_file = request.FILES['file']\n```\n\n**Settings:**\n• MEDIA_URL - URL for uploaded files\n• MEDIA_ROOT - Directory for uploaded files\n• FILE_UPLOAD_MAX_MEMORY_SIZE - Memory threshold\n\n**Security:**\n• Validate file types\n• Limit file sizes\n• Scan for malware\n• Use secure file names
Question:
What are Django Generic Views and when to use them?
Answer:
Django Generic Views provide common functionality:\n\n**Display Views:**\n• ListView - Display list of objects\n• DetailView - Display single object\n\n**Editing Views:**\n• CreateView - Create new object\n• UpdateView - Update existing object\n• DeleteView - Delete object\n• FormView - Handle form processing\n\n**Example:**\n```python\nclass BookListView(ListView):\n model = Book\n template_name = 'books/list.html'\n context_object_name = 'books'\n paginate_by = 10\n```\n\n**Benefits:**\n• Reduce code duplication\n• Built-in pagination\n• Standard patterns\n• Easy customization\n\n**When to use:**\n• Standard CRUD operations\n• Simple display logic\n• Rapid prototyping
Question:
How do you implement pagination in Django?
Answer:
Django pagination implementation:\n\n**Using Paginator:**\n```python\nfrom django.core.paginator import Paginator\n\ndef book_list(request):\n books = Book.objects.all()\n paginator = Paginator(books, 10) # 10 per page\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n return render(request, 'books.html', {'page_obj': page_obj})\n```\n\n**In Template:**\n```html\n{% for book in page_obj %}\n {{ book.title }}\n{% endfor %}\n\n\n```\n\n**Class-based Views:**\n• Set paginate_by attribute\n• Automatic pagination handling
Question:
What are Django middleware and how do they work?
Answer:
Middleware are hooks into Django's request/response processing. They process requests before views and responses after views.
Common middleware:
• SecurityMiddleware
• SessionMiddleware
• AuthenticationMiddleware
• CsrfViewMiddleware
Custom middleware:
• Implement process_request, process_view, process_response, process_exception methods
• Order matters in MIDDLEWARE setting
Question:
Explain Django authentication and authorization system.
Answer:
Authentication verifies user identity, Authorization determines permissions.
Components:
• User model
• Groups
• Permissions
• Authentication backends
Features:
• Login/logout views
• Password management
• Permission decorators (@login_required, @permission_required)
• Custom user models
• Social authentication support
User model fields:
• username, email, password
• is_active, is_staff, is_superuser
Question:
What are Django signals and when to use them?
Answer:
Signals allow decoupled applications to get notified when actions occur.
Common signals:
• pre_save, post_save
• pre_delete, post_delete
• m2m_changed
Use cases:
• Logging
• Cache invalidation
• Email notifications
• Profile creation
Example:
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
# Profile creation logic
Benefits:
• Loose coupling
• Event-driven architecture
Question:
Explain Django QuerySet optimization techniques.
Answer:
Optimization techniques:
• select_related() - JOIN for ForeignKey/OneToOne
• prefetch_related() - separate queries for ManyToMany/reverse FK
• only() - limit fields
• defer() - exclude fields
• bulk_create() - bulk operations
• exists() - check existence
• count() - count records
• iterator() - memory-efficient iteration
• database indexes
• query analysis with django-debug-toolbar
Question:
What is Django REST Framework and its key components?
Answer:
DRF is a toolkit for building Web APIs in Django.
Key components:
• Serializers - convert model instances to JSON
• ViewSets - handle API logic
• Routers - URL routing
• Authentication - token, session, JWT
• Permissions - access control
• Throttling - rate limiting
• Pagination
• Filtering
• Versioning
Benefits:
• Browsable API
• Flexible serialization
• Comprehensive authentication
Question:
Explain Django caching strategies and implementation.
Answer:
Caching improves performance by storing computed data.
Types:
• Per-site cache - entire site
• Per-view cache - @cache_page decorator
• Template fragment cache - {% cache %}
• Low-level cache API
Backends:
• Database
• File system
• Memcached
• Redis
Features:
• Cache keys, timeouts, versioning
• Cache invalidation strategies
Example:
from django.core.cache import cache
cache.set('key', 'value', 300)
Question:
How do you handle database transactions in Django?
Answer:
Django provides transaction management:
• Autocommit mode (default)
• atomic() decorator/context manager
• transaction.on_commit() for post-commit actions
• Savepoints for nested transactions
Database-level transactions ensure ACID properties.
Example:
@transaction.atomic
def my_view(request):
# All database operations in single transaction
# Rollback on exceptions
Question:
Explain Django security features and best practices.
Answer:
Security features:
• CSRF protection (tokens)
• XSS protection (auto-escaping)
• SQL injection prevention (ORM)
• Clickjacking protection (X-Frame-Options)
• HTTPS enforcement
• Secure cookies
• Password validation
• User input validation
Best practices:
• Keep Django updated
• Use HTTPS
• Validate all inputs
• Implement proper authentication
• Use security middleware
• Regular security audits
Question:
What are Django custom model managers and when to use them?
Answer:
Custom managers modify initial QuerySet or add extra manager methods.
Use cases:
• Filter default QuerySet
• Add custom query methods
• Modify model creation
Example:
class PublishedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='published')
Benefits:
• Encapsulate common queries
• Improve code reusability
• Cleaner model API
Question:
How do you implement custom Django middleware?
Answer:
Custom middleware implementation:\n\n**Class-based middleware:**\n```python\nclass CustomMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n \n def __call__(self, request):\n # Process request\n response = self.get_response(request)\n # Process response\n return response\n \n def process_view(self, request, view_func, view_args, view_kwargs):\n # Called before view\n pass\n```\n\n**Registration:**\n• Add to MIDDLEWARE setting in settings.py\n• Order matters - middleware executes in order\n\n**Use cases:**\n• Authentication\n• Logging\n• Request modification\n• Response headers
Question:
Explain Django's testing framework and best practices.
Answer:
Django testing framework:\n\n**Test Classes:**\n• TestCase - Full Django test case with database\n• TransactionTestCase - Test database transactions\n• SimpleTestCase - No database access\n• LiveServerTestCase - Runs live server\n\n**Test Methods:**\n• setUp() - Run before each test\n• tearDown() - Run after each test\n• setUpClass() - Run once before all tests\n\n**Assertions:**\n• assertEqual(), assertTrue(), assertFalse()\n• assertContains(), assertRedirects()\n• assertRaises(), assertTemplateUsed()\n\n**Best Practices:**\n• Use factories for test data\n• Mock external services\n• Test edge cases\n• Keep tests isolated\n• Use descriptive test names
Question:
Explain Django's session framework and configuration.
Answer:
Django session framework:\n\n**Session Engines:**\n• Database sessions (default)\n• File-based sessions\n• Cache-based sessions\n• Cookie-based sessions\n\n**Configuration:**\n```python\nSESSION_ENGINE = 'django.contrib.sessions.backends.db'\nSESSION_COOKIE_AGE = 1209600 # 2 weeks\nSESSION_COOKIE_SECURE = True # HTTPS only\nSESSION_COOKIE_HTTPONLY = True # No JavaScript access\n```\n\n**Usage:**\n```python\n# Set session data\nrequest.session['key'] = 'value'\n\n# Get session data\nvalue = request.session.get('key')\n\n# Delete session data\ndel request.session['key']\n```\n\n**Security:**\n• Use secure cookies in production\n• Set appropriate expiration\n• Regenerate session ID on login
Question:
What are Django model validators and how to create custom ones?
Answer:
Django model validators:\n\n**Built-in Validators:**\n• EmailValidator\n• URLValidator\n• RegexValidator\n• MinLengthValidator, MaxLengthValidator\n• MinValueValidator, MaxValueValidator\n\n**Custom Validator Function:**\n```python\nfrom django.core.exceptions import ValidationError\n\ndef validate_even(value):\n if value % 2 != 0:\n raise ValidationError('%(value)s is not even', params={'value': value})\n\nclass MyModel(models.Model):\n number = models.IntegerField(validators=[validate_even])\n```\n\n**Custom Validator Class:**\n```python\nclass RangeValidator:\n def __init__(self, min_val, max_val):\n self.min_val = min_val\n self.max_val = max_val\n \n def __call__(self, value):\n if not (self.min_val <= value <= self.max_val):\n raise ValidationError(f'Value must be between {self.min_val} and {self.max_val}')\n```\n\n**Model-level Validation:**\n• Override clean() method\n• Called during form validation
Question:
Explain Django's logging configuration and best practices.
Answer:
Django logging configuration:\n\n**Settings Configuration:**\n```python\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose': {\n 'format': '{levelname} {asctime} {module} {message}',\n 'style': '{',\n },\n },\n 'handlers': {\n 'file': {\n 'level': 'INFO',\n 'class': 'logging.FileHandler',\n 'filename': 'django.log',\n 'formatter': 'verbose',\n },\n },\n 'loggers': {\n 'django': {\n 'handlers': ['file'],\n 'level': 'INFO',\n 'propagate': True,\n },\n },\n}\n```\n\n**Usage:**\n```python\nimport logging\nlogger = logging.getLogger(__name__)\nlogger.info('User logged in')\n```\n\n**Best Practices:**\n• Use appropriate log levels\n• Include contextual information\n• Rotate log files\n• Monitor logs in production
Question:
How do you implement custom Django management commands?
Answer:
Custom Django management commands:\n\n**Directory Structure:**\n```\nmyapp/\n management/\n __init__.py\n commands/\n __init__.py\n my_command.py\n```\n\n**Command Implementation:**\n```python\nfrom django.core.management.base import BaseCommand\nfrom django.contrib.auth.models import User\n\nclass Command(BaseCommand):\n help = 'Create sample users'\n \n def add_arguments(self, parser):\n parser.add_argument('--count', type=int, default=10)\n parser.add_argument('--prefix', type=str, default='user')\n \n def handle(self, *args, **options):\n count = options['count']\n prefix = options['prefix']\n \n for i in range(count):\n User.objects.create_user(\n username=f'{prefix}{i}',\n email=f'{prefix}{i}@example.com'\n )\n \n self.stdout.write(\n self.style.SUCCESS(f'Created {count} users')\n )\n```\n\n**Usage:**\n```bash\npython manage.py my_command --count 5 --prefix test\n```\n\n**Use Cases:**\n• Data migration\n• Cleanup tasks\n• Batch operations\n• Scheduled jobs
Question:
What is Django's contenttypes framework and its applications?
Answer:
Django contenttypes framework:\n\n**Purpose:**\n• Create generic relationships between models\n• Reference any model from any other model\n• Build reusable applications\n\n**Implementation:**\n```python\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.contrib.contenttypes.models import ContentType\n\nclass Comment(models.Model):\n content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)\n object_id = models.PositiveIntegerField()\n content_object = GenericForeignKey('content_type', 'object_id')\n text = models.TextField()\n\n# Usage\npost = BlogPost.objects.get(id=1)\ncomment = Comment.objects.create(\n content_object=post,\n text='Great post!'\n)\n```\n\n**Generic Relations:**\n```python\nfrom django.contrib.contenttypes.fields import GenericRelation\n\nclass BlogPost(models.Model):\n comments = GenericRelation(Comment)\n```\n\n**Applications:**\n• Tagging systems\n• Activity feeds\n• Comments/ratings\n• Notifications\n• Audit trails
Question:
Explain Django's internationalization (i18n) and localization (l10n).
Answer:
Django internationalization and localization:\n\n**Settings:**\n```python\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\nLANGUAGE_CODE = 'en-us'\nLANGUAGES = [\n ('en', 'English'),\n ('es', 'Spanish'),\n ('fr', 'French'),\n]\nLOCALE_PATHS = [os.path.join(BASE_DIR, 'locale')]\n```\n\n**Marking Strings for Translation:**\n```python\nfrom django.utils.translation import gettext as _\n\ndef my_view(request):\n message = _('Hello, world!')\n return render(request, 'template.html', {'message': message})\n```\n\n**In Templates:**\n```html\n{% load i18n %}\n{% trans \"Welcome\" %}\n{% blocktrans %}Hello {{ name }}{% endblocktrans %}\n```\n\n**Commands:**\n• django-admin makemessages - Extract translatable strings\n• django-admin compilemessages - Compile translations\n\n**Features:**\n• Plural forms\n• Context-specific translations\n• Lazy translations\n• Time zone support\n• Number/date formatting
Question:
How do you optimize Django application performance?
Answer:
Django performance optimization strategies:\n\n**Database Optimization:**\n• Use select_related() for ForeignKey/OneToOne\n• Use prefetch_related() for ManyToMany/reverse FK\n• Add database indexes\n• Use only() and defer() to limit fields\n• Optimize queries with explain()\n• Use bulk operations (bulk_create, bulk_update)\n\n**Caching:**\n• Per-site caching\n• Per-view caching with @cache_page\n• Template fragment caching\n• Low-level cache API\n• Database query caching\n\n**Template Optimization:**\n• Use template inheritance\n• Minimize template logic\n• Cache template fragments\n• Use {% load %} tags efficiently\n\n**Static Files:**\n• Use CDN for static files\n• Enable compression (gzip)\n• Minify CSS/JavaScript\n• Use HTTP caching headers\n\n**Code Optimization:**\n• Profile with django-debug-toolbar\n• Use pagination for large datasets\n• Optimize Python code\n• Use connection pooling\n• Enable database query logging