Title: Django Framework — LearnCoachAssist

Q: What is Django?
A: Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the MTV (Model-Template-View) architectural pattern and includes built-in features like an ORM, admin interface, and authentication system.

Q: What is the Django MTV pattern?
A: MTV stands for Model-Template-View:
- Model – defines data structure and database schema
- Template – handles the presentation layer (HTML)
- View – contains business logic and returns responses

Q: How do you create a new Django project?
A: Use the command:
django-admin startproject myproject
This generates the project directory with settings.py, urls.py, wsgi.py, asgi.py, and manage.py.

Q: How do you create a new Django app?
A: Run:
python manage.py startapp myapp
Then add 'myapp' to the INSTALLED_APPS list in settings.py to register it with the project.

Q: What is a Django model?
A: A Django model is a Python class that subclasses django.db.models.Model. Each model maps to a single database table, and each attribute represents a database column. Example:
class Article(models.Model):
  title = models.CharField(max_length=200)

Q: What are common Django model field types?
A: Common field types include:
- CharField – short text (requires max_length)
- TextField – long text
- IntegerField – integers
- BooleanField – True/False
- DateTimeField – date and time
- ForeignKey – many-to-one relationship
- ManyToManyField – many-to-many relationship

Q: What is the Django ORM?
A: The Object-Relational Mapper (ORM) lets you interact with the database using Python code instead of raw SQL. You use model classes and querysets like MyModel.objects.filter(active=True) to query, create, update, and delete records.

Q: How do you retrieve all objects from a model?
A: Use the all() method on the model's manager:
all_articles = Article.objects.all()
This returns a QuerySet containing all rows in the corresponding table.

Q: How do you filter querysets in Django?
A: Use filter() and exclude():
Article.objects.filter(status='published')
Article.objects.exclude(status='draft')
You can chain lookups like title__icontains='django', date__gte=some_date, and author__name='Alice'.

Q: What is the difference between filter() and get() in Django ORM?
A: filter() returns a QuerySet (zero or more objects), while get() returns a single object or raises exceptions:
- DoesNotExist – if no match is found
- MultipleObjectsReturned – if more than one match exists

Q: What are Django migrations?
A: Migrations are version-controlled changes to your database schema. Key commands:
python manage.py makemigrations – creates migration files from model changes
python manage.py migrate – applies migrations to the database
They are stored as Python files in each app's migrations/ directory.

Q: How do you roll back a migration in Django?
A: Specify the migration name to revert to:
python manage.py migrate myapp 0003_previous
To undo all migrations for an app:
python manage.py migrate myapp zero

Q: What is a Django function-based view (FBV)?
A: A function-based view is a Python function that takes an HttpRequest and returns an HttpResponse:
def hello(request):
  return HttpResponse("Hello, World!")

Q: What is a Django class-based view (CBV)?
A: A class-based view subclasses django.views.View or a generic view. It maps HTTP methods to class methods:
class ArticleView(View):
  def get(self, request):
    return HttpResponse("Articles")
Use ArticleView.as_view() in URL configuration.

Q: What are Django generic class-based views?
A: Generic views handle common patterns out of the box:
- ListView – display a list of objects
- DetailView – display a single object
- CreateView – form to create an object
- UpdateView – form to update an object
- DeleteView – confirm and delete an object
Import from django.views.generic.

Q: How does Django URL routing work?
A: URLs are mapped to views in urls.py using urlpatterns:
from django.urls import path
urlpatterns = [
  path('articles/', views.article_list, name='article-list'),
  path('articles/<int:pk>/', views.article_detail, name='article-detail'),
]
Use include() to reference other app URL configs.

Q: What are URL path converters in Django?
A: Path converters capture parts of the URL as typed parameters:
- <int:pk> – matches integers
- <str:slug> – matches non-empty strings (excluding /)
- <slug:slug> – matches slugs (letters, numbers, hyphens, underscores)
- <uuid:id> – matches UUIDs

Q: What is the Django template language?
A: Django's template engine uses HTML files with special syntax:
- {{ variable }} – output a variable
- {% tag %} – template tags for logic (if, for, block)
- {{ value|filter }} – apply filters like date, length, lower
Templates are stored in the app's templates/ directory.

Q: What is template inheritance in Django?
A: Template inheritance lets you define a base template with {% block %} placeholders that child templates override:
{% extends "base.html" %}
{% block content %}
  <h1>My Page</h1>
{% endblock %}
This promotes DRY (Don't Repeat Yourself) design.

Q: How do you pass context to a Django template?
A: In a view, pass a dictionary to render():
def my_view(request):
  context = {'articles': Article.objects.all()}
  return render(request, 'my_template.html', context)
Variables are then accessible as {{ articles }} in the template.

Q: What is the Django admin site?
A: The Django admin is an auto-generated web interface for managing your data. Register models in admin.py:
from django.contrib import admin
from .models import Article
admin.site.register(Article)
Access it at /admin/ after creating a superuser with python manage.py createsuperuser.

Q: How do you customize the Django admin?
A: Create a ModelAdmin class:
class ArticleAdmin(admin.ModelAdmin):
  list_display = ['title', 'status', 'created']
  list_filter = ['status']
  search_fields = ['title', 'body']
admin.site.register(Article, ArticleAdmin)
You can also use the @admin.register(Article) decorator.

Q: What are Django forms?
A: Django forms handle HTML form rendering, validation, and data cleaning. Define a form class:
from django import forms
class ContactForm(forms.Form):
  name = forms.CharField(max_length=100)
  email = forms.EmailField()
Use form.is_valid() to validate and form.cleaned_data to access results.

Q: What is a Django ModelForm?
A: A ModelForm automatically creates form fields from a model:
class ArticleForm(forms.ModelForm):
  class Meta:
    model = Article
    fields = ['title', 'body', 'status']
Calling form.save() directly creates or updates the database record.

Q: How do you handle form validation in Django?
A: Django provides multiple validation layers:
- Field-level – built-in validators and clean_<fieldname>() methods
- Form-level – override clean() for cross-field validation
- Model-level – model validators and the clean() method on models
Errors are stored in form.errors.

Q: What is Django middleware?
A: Middleware is a framework of hooks that processes requests and responses globally. Each middleware is a class with methods like __call__, process_view, and process_exception. They are defined in the MIDDLEWARE setting and executed in order for requests and in reverse for responses.

Q: What are some built-in Django middleware classes?
A: Key built-in middleware:
- SecurityMiddleware – HTTPS redirects, HSTS headers
- SessionMiddleware – session support
- CommonMiddleware – URL rewriting, content length
- CsrfViewMiddleware – CSRF protection
- AuthenticationMiddleware – attaches request.user
- MessageMiddleware – flash messages

Q: How does Django authentication work?
A: Django's django.contrib.auth provides:
- User model – stores credentials and profile info
- authenticate() – verifies credentials
- login() / logout() – manages sessions
- @login_required – decorator to protect views
- Permission system – per-object and per-model permissions

Q: How do you create a custom user model in Django?
A: Subclass AbstractUser or AbstractBaseUser and set AUTH_USER_MODEL in settings:
class CustomUser(AbstractUser):
  phone = models.CharField(max_length=15, blank=True)
In settings.py:
AUTH_USER_MODEL = 'myapp.CustomUser'
Do this before the first migration.

Q: What is the @login_required decorator?
A: @login_required restricts a view to authenticated users only:
from django.contrib.auth.decorators import login_required
@login_required(login_url='/login/')
def dashboard(request):
  return render(request, 'dashboard.html')
Unauthenticated users are redirected to the login URL.

Q: What is CSRF protection in Django?
A: Django protects against Cross-Site Request Forgery attacks using a token-based system. Include {% csrf_token %} in every POST form. The CsrfViewMiddleware verifies that the submitted token matches the one stored in the user's session.

Q: What security features does Django provide?
A: Django includes built-in protection against:
- CSRF – token-based form protection
- XSS – automatic template escaping
- SQL Injection – parameterized ORM queries
- Clickjacking – X-Frame-Options middleware
- HTTPS – SecurityMiddleware, HSTS support
- Password hashing – PBKDF2 by default

Q: What are Django signals?
A: Signals allow decoupled components to be notified when certain actions occur. Common signals:
- pre_save / post_save – before/after model save
- pre_delete / post_delete – before/after model delete
- request_started / request_finished
Connect with @receiver(post_save, sender=MyModel).

Q: How do you create a custom Django signal?
A: Define and dispatch a signal:
import django.dispatch
order_completed = django.dispatch.Signal()
Send it:
order_completed.send(sender=self.__class__, order=order)
Receive it:
@receiver(order_completed)
def handle_order(sender, order, **kwargs):
  send_confirmation_email(order)

Q: How do you serve static files in Django?
A: Configure in settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_ROOT = BASE_DIR / 'staticfiles'
In templates use {% load static %} and {% static 'css/style.css' %}. Run python manage.py collectstatic for production.

Q: How do you handle media files (user uploads) in Django?
A: Configure in settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
Use FileField or ImageField in models. In development, add to urls.py:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Q: What is a Django management command?
A: Management commands are run via manage.py. Create custom ones in myapp/management/commands/mycommand.py:
from django.core.management.base import BaseCommand
class Command(BaseCommand):
  help = 'My custom command'
  def handle(self, *args, **options):
    self.stdout.write('Done!')
Run with python manage.py mycommand.

Q: What is Django REST Framework (DRF)?
A: DRF is a powerful toolkit for building Web APIs in Django. Key components:
- Serializers – convert models to/from JSON
- ViewSets – group related API views
- Routers – auto-generate URL patterns
- Authentication – token, session, JWT support
- Browsable API – web interface for testing

Q: What is a DRF serializer?
A: A serializer converts complex data types (models, querysets) to native Python types for JSON rendering and vice versa:
from rest_framework import serializers
class ArticleSerializer(serializers.ModelSerializer):
  class Meta:
    model = Article
    fields = ['id', 'title', 'body']

Q: What is the difference between Serializer and ModelSerializer in DRF?
A: Serializer requires you to define each field manually and implement create() and update() methods.
ModelSerializer automatically generates fields from the model and provides default create() and update() implementations. It also auto-generates validators based on model constraints.

Q: What are Django QuerySet methods for aggregation?
A: Use aggregate() and annotate() with functions from django.db.models:
from django.db.models import Count, Avg, Sum
Article.objects.aggregate(total=Count('id'))
Author.objects.annotate(num_articles=Count('article'))
aggregate() returns a dict; annotate() adds fields to each object.

Q: What is the Django Q object?
A: Q objects enable complex lookups with OR, AND, and NOT operators:
from django.db.models import Q
Article.objects.filter(
  Q(status='published') | Q(author=request.user)
)
Without Q, multiple filter() arguments are combined with AND only.

Q: What is the Django F expression?
A: F() references a model field value directly in the database, avoiding a Python round-trip:
from django.db.models import F
Article.objects.update(views=F('views') + 1)
This performs the increment atomically in SQL, preventing race conditions.

Q: What are Django model managers?
A: A Manager is the interface for database query operations. The default is objects. Create custom managers for reusable queries:
class PublishedManager(models.Manager):
  def get_queryset(self):
    return super().get_queryset().filter(status='published')
Assign with published = PublishedManager() in your model.

Q: What is select_related() in Django?
A: select_related() performs a SQL JOIN to fetch related objects in a single query, reducing database hits for ForeignKey and OneToOneField relationships:
articles = Article.objects.select_related('author').all()
Use prefetch_related() instead for ManyToManyField and reverse relations.

Q: What is prefetch_related() in Django?
A: prefetch_related() performs separate queries for each relationship and joins them in Python. Ideal for ManyToMany and reverse FK relations:
authors = Author.objects.prefetch_related('articles')
Unlike select_related(), it works with any relationship type but uses multiple queries.

Q: What are Django context processors?
A: Context processors are functions that add variables to every template context automatically. They are defined in the TEMPLATES setting. Built-in processors include auth (adds user), request, messages, and debug. Custom example:
def site_name(request):
  return {'SITE_NAME': 'My Site'}

Q: What is Django's session framework?
A: Django sessions store arbitrary data per visitor on the server side. Enable via SessionMiddleware. Access in views:
request.session['cart'] = cart_data
cart = request.session.get('cart', [])
Backends include database, cache, file, and cookie-based sessions.

Q: How do you write tests in Django?
A: Django extends Python's unittest with TestCase:
from django.test import TestCase
class ArticleTests(TestCase):
  def setUp(self):
    Article.objects.create(title='Test')
  def test_article_str(self):
    a = Article.objects.get(id=1)
    self.assertEqual(str(a), 'Test')
Run with python manage.py test.

Q: What is the Django test client?
A: The test Client simulates HTTP requests without a running server:
from django.test import Client
c = Client()
response = c.get('/articles/')
self.assertEqual(response.status_code, 200)
response = c.post('/login/', {'user': 'admin', 'pass': 'secret'})
It handles cookies, sessions, and redirects.

Q: Which command creates a Django project AND its initial app skeleton in one step (Django 1.6+)?
A: django-admin startproject mysite && cd mysite && django-admin startapp myapp
Note: manage.py is generated with the project, but apps must still be created separately and added to INSTALLED_APPS.

Q: What is the role of manage.py?
A: manage.py is a thin wrapper around django-admin that sets the DJANGO_SETTINGS_MODULE to the project's settings.py. It is the recommended entry point for project-level commands like migrate, runserver, and shell.

Q: What is the purpose of wsgi.py in a Django project?
A: wsgi.py exposes a WSGI-compatible callable (application) used by production servers like Gunicorn, uWSGI, or mod_wsgi. It is the entry point for synchronous request handling under WSGI.

Q: What is the purpose of asgi.py in a Django project?
A: asgi.py exposes an ASGI-compatible callable for servers like Daphne or Uvicorn. It enables async views, WebSockets, and long-lived connections (e.g. Django Channels).

Q: What does the settings.py file contain?
A: settings.py is the central configuration module: INSTALLED_APPS, MIDDLEWARE, DATABASES, TEMPLATES, STATIC_URL, STATIC_ROOT, MEDIA_URL, MEDIA_ROOT, ALLOWED_HOSTS, SECRET_KEY, DEBUG, USE_TZ, and auth/password validators.

Q: What is the purpose of urls.py at the project level?
A: The project-level urls.py is the root URLconf. It usually contains urlpatterns that delegate to app-level urls.py files via include().
Example:
path('blog/', include('blog.urls'))

Q: What is the apps.py file in a Django app?
A: apps.py contains the AppConfig subclass for the app. It registers metadata like name and verbose_name and can run startup code in ready() (e.g. registering signals).

Q: What is tests.py used for in a Django app?
A: tests.py is the conventional location for unit and integration tests. It is discovered automatically by python manage.py test (any class subclassing unittest.TestCase or django.test.TestCase).

Q: What is the default Django database backend?
A: By default, Django uses SQLite via the django.db.backends.sqlite3 engine. For production, common choices are postgresql, mysql, or oracle via the django.db.backends.* module.

Q: How do you configure a PostgreSQL database in Django?
A: In settings.py:
DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.postgresql',
    'NAME': 'mydb',
    'USER': 'mydbuser',
    'PASSWORD': 'secret',
    'HOST': 'localhost',
    'PORT': '5432',
  }
}

Q: How do you set the time zone in Django?
A: Use TIME_ZONE = 'Europe/Zagreb' in settings.py. Also enable USE_TZ = True so Django stores datetimes in UTC and converts on output. LANGUAGE_CODE is a separate setting that controls translation.

Q: What is DEBUG mode and why should it be off in production?
A: DEBUG = True enables detailed tracebacks and the technical 500 page. It must be False in production because it leaks settings, environment variables, and query information to anyone who triggers an error.

Q: What does ALLOWED_HOSTS do?
A: ALLOWED_HOSTS is a list of valid host/domain names the site can serve. Django rejects requests with an HTTP 400 if the Host header is not in this list, preventing HTTP Host header attacks.

Q: How do you set the SECRET_KEY safely?
A: SECRET_KEY should be loaded from an environment variable:
SECRET_KEY = os.environ['DJANGO_SECRET_KEY']
It is used for signing cookies, password reset tokens, CSRF, and crypto signing. Never commit it to version control.

Q: What is the __str__ method on a model used for?
A: Defining __str__(self) returns a human-readable string representation of a model instance. The Django admin and shell display this value, and it is used by default in ModelChoiceField.

Q: What is the Meta class inside a Django model?
A: The inner Meta class holds model-level options:
class Meta:
  ordering = ['-created']
  verbose_name = 'article'
  db_table = 'blog_article'
  unique_together = [('title', 'slug')]
It does not define database fields.

Q: What does the related_name argument do on a ForeignKey?
A: related_name='articles' sets the reverse accessor name from the related model. Without it, Django uses <modelname>_set:
author.articles.all() # uses related_name
author.article_set.all() # default

Q: What is the on_delete argument on a ForeignKey?
A: on_delete specifies behavior when the referenced object is deleted. Options include:
- models.CASCADE – delete dependents
- models.PROTECT – block deletion
- models.SET_NULL – set FK to NULL (requires null=True)
- models.SET_DEFAULT – set to default value
- models.DO_NOTHING – no action (may raise IntegrityError)

Q: What is the difference between null=True and blank=True?
A: null=True allows NULL at the database column level; blank=True allows the field to be empty in forms. Common pattern:
description = models.TextField(null=True, blank=True)
For string-based fields, prefer blank=True alone (empty string instead of NULL).

Q: How do you add a database index to a model field?
A: Use db_index=True:
title = models.CharField(max_length=200, db_index=True)
For composite indexes use Meta.indexes = [models.Index(fields=['author', '-published'])].

Q: What does Meta.constraints allow?
A: Meta.constraints defines database-level integrity rules such as models.UniqueConstraint and models.CheckConstraint. They run at the database layer and are enforced even when bypassing the ORM.

Q: What is a OneToOneField in Django?
A: A OneToOneField represents a strict 1:1 link between two models. Common use: extending the User model with a Profile:
user = models.OneToOneField(User, on_delete=models.CASCADE)
It is implemented as a UNIQUE FK.

Q: How do you define a many-to-many relationship in Django?
A: Use ManyToManyField on one of the models:
tags = models.ManyToManyField(Tag)
Django creates an auto-generated join table. You can also pass through='ThroughModel' to use a custom intermediate model with extra fields.

Q: What is a through model in a M2M relationship?
A: A through model is an explicit intermediate model that stores extra fields on a many-to-many relationship, such as joined_at or role. It must contain two ForeignKeys to the participating models.

Q: What is the difference between values() and values_list() in Django?
A: values() returns dictionaries of field values; values_list() returns tuples. With flat=True and a single field, values_list() returns a flat list:
Article.objects.values_list('id', flat=True)

Q: What does only() and defer() do in a QuerySet?
A: only('title', 'body') limits the SQL SELECT to those fields. defer('body') excludes fields and loads them on demand. Useful for large TextField columns to avoid unnecessary I/O.

Q: What is the difference between count() and len(queryset)?
A: queryset.count() issues SELECT COUNT(*) in the database. len(queryset) forces evaluation of the full queryset and counts in Python. Always use .count() for large tables.

Q: What does exists() do on a QuerySet?
A: queryset.exists() returns True/False by issuing a fast SELECT 1 ... LIMIT 1. It is cheaper than len(queryset) > 0 or queryset.count() > 0 when you only need to know whether any row matches.

Q: What is the difference between order_by() and the Meta.ordering attribute?
A: Meta.ordering = ['-created'] sets a default ordering applied automatically to every queryset. order_by('title', '-created') overrides it for a specific query.

Q: What is a subquery in Django ORM?
A: Use Subquery() from django.db.models to embed a queryset in another:
latest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created')[:1]
Post.objects.annotate(last_comment=Subquery(latest.values('body')))

Q: What is the Exists() subquery expression?
A: Exists() from django.db.models returns a boolean subquery used in filter() or annotate():
Author.objects.annotate(
  has_posts=Exists(Post.objects.filter(author=OuterRef('pk')))
)
It generates a correlated EXISTS SQL clause.

Q: What is the N+1 query problem in Django?
A: It occurs when ORM code accesses related objects in a loop, triggering one extra query per parent row. Fix with select_related() or prefetch_related() in the initial queryset.

Q: What is the difference between .first() and [0] on a queryset?
A: .first() returns None when the queryset is empty. Indexing with [0] raises IndexError. Prefer .first() when the queryset may be empty.

Q: What is a database transaction in Django?
A: A transaction groups multiple SQL operations so they commit or roll back atomically. Use transaction.atomic:
from django.db import transaction
with transaction.atomic():
  Item.objects.create(...)
  Log.objects.create(...)

Q: What is select_for_update() used for?
A: select_for_update() locks the selected rows for the duration of the current transaction (row-level SELECT ... FOR UPDATE in PostgreSQL). It prevents race conditions when reading then updating a counter or stock value.

Q: How do you bulk create objects in Django?
A: Use bulk_create():
Article.objects.bulk_create([
  Article(title='A'), Article(title='B')
])
It issues a single INSERT and skips per-row save() signals.

Q: How do you update many records at once?
A: Use the queryset update() method:
Article.objects.filter(status='draft').update(status='published')
This runs a single UPDATE SQL statement and bypasses save() signals.

Q: How do you delete many records at once?
A: Use the queryset delete() method:
Article.objects.filter(created__year=2024).delete()
It returns a tuple (total_deleted, {model_label: count}).

Q: What is the get_or_create() method?
A: get_or_create(defaults=None, **kwargs) returns (object, created). It looks up a record by kwargs; if missing, it creates one using defaults plus kwargs.
obj, created = Tag.objects.get_or_create(name='python')

Q: What is the update_or_create() method?
A: update_or_create(defaults=None, **kwargs) either updates an existing record matching kwargs with defaults, or creates a new one. Returns (object, created).

Q: What are QuerySet.union(), intersection(), and difference()?
A: These set-operation methods combine querysets from the same model:
- qs1.union(qs2) – SQL UNION (distinct)
- qs1.intersection(qs2) – SQL INTERSECT
- qs1.difference(qs2) – SQL EXCEPT
They require identical field lists and disable ordering.

Q: What does reverse_lazy do and when is it used?
A: reverse_lazy returns a URL string evaluated lazily. It is required when referencing URL reverses in module-level code (e.g. success_url attributes on class-based views, signal handlers) because URLs are not loaded yet at import time.

Q: What is the url template tag?
A: {% url 'name' arg1 arg2 %} resolves a named URL pattern to its path. It accepts either positional args matching path converters or keyword args:
<a href="{% url 'article-detail' pk=article.id %}">Read</a>

Q: What is the include template tag?
A: {% include 'partials/card.html' with article=obj %} renders another template inline, optionally passing context. It is the recommended way to share small reusable snippets without inheriting from a base template.

Q: What are template filters in Django?
A: Filters transform template variables:
- {{ name|lower }} – lowercase
- {{ text|truncatewords:20 }} – truncate
- {{ value|default:'N/A' }} – fallback value
- {{ html|safe }} – mark as safe (no escaping)
- {{ date|date:'Y-m-d' }} – format date
You can chain them: {{ value|lower|truncatechars:30 }}

Q: How do you create a custom template filter?
A: Register a Python function in a templatetags/ module:
from django import template
register = template.Library()
@register.filter
def shout(value):
  return value.upper() + '!'
Load with {% load myfilters %} in templates.

Q: What is the static template tag?
A: {% load static %} then <link rel="stylesheet" href="{% static 'css/main.css' %}">. It prepends STATIC_URL to the relative path and applies any storage backends configured.

Q: What is the csrf_token template tag?
A: {% csrf_token %} inserts a hidden input containing the CSRF token bound to the user's session. Required inside every <form method="post"> for the CsrfViewMiddleware to accept the submission.

Q: What is the forloop variable in template loops?
A: Inside {% for item in items %} the forloop object exposes:
- forloop.counter – 1-indexed count
- forloop.counter0 – 0-indexed count
- forloop.first / forloop.last – booleans
- forloop.parentloop – outer loop context

Q: What does {% empty %} do in a template for loop?
A: {% empty %} inside {% for ... %} renders the fallback block when the iterable is empty:
{% for a in articles %}
  {{ a.title }}
{% empty %}
  No articles yet.
{% endfor %}

Q: What are template context processors?
A: Functions in TEMPLATES.OPTIONS.context_processors that inject variables into every template. Built-ins include django.template.context_processors.request (adds request), auth (adds user and perms), and messages.

Q: How do you register a custom context processor?
A: Define a function taking request and returning a dict, then add its dotted path to TEMPLATES.OPTIONS.context_processors in settings.py.

Q: What is the messages framework?
A: django.contrib.messages is a one-time notification system. In views:
messages.success(request, 'Saved!')
In templates: {% if messages %}{% for m in messages %}<div class="alert">{{ m }}</div>{% endfor %}{% endif %}
Messages are stored in the session or cookie and shown once.

Q: What is the messages framework's default storage level?
A: MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' by default. It uses the user's session, so SessionMiddleware must be enabled. Other options include cookie-based storage.

Q: What is a Django app and how is it different from a project?
A: A project is the entire Django installation (settings, root URLconf). An app is a self-contained Python package that handles a feature (blog, accounts, polls). A project contains many apps; an app can be reused across projects.

Q: How do you reuse an app across projects?
A: Place the app on the PYTHONPATH, add it to INSTALLED_APPS, and ship its migrations/, templates, and static files with it. Using a custom AppConfig in apps.py lets you encapsulate signals and ready-time setup.

Q: What is the apps.AppConfig.ready() method used for?
A: Override ready() in your AppConfig to perform import-time setup, such as registering signals, connecting checks, or initializing third-party clients. It runs once when the app registry is populated.

Q: What does request.user return when a user is anonymous?
A: request.user is always populated by AuthenticationMiddleware. For anonymous visitors it returns an instance of django.contrib.auth.models.AnonymousUser with is_authenticated == False and is_anonymous == True.

Q: What is the difference between is_authenticated and is_anonymous?
A: request.user.is_authenticated is True for logged-in users and False for AnonymousUser. is_anonymous is the opposite. Always check is_authenticated in views; AnonymousUser exists for symmetry, not for security checks.

Q: What is the @permission_required decorator?
A: @permission_required('app.add_article') checks that request.user has the named permission; otherwise it returns 403 or redirects to LOGIN_URL.
Permissions follow the <app_label>.<action>_<modelname> convention.

Q: What are Django groups used for?
A: django.contrib.auth.models.Group lets you bundle permissions and assign them to multiple users at once. A user in a group inherits the group's permissions automatically.

Q: How does Django hash passwords?
A: Django uses PBKDF2 + SHA256 by default (django.contrib.auth.hashers.PBKDF2PasswordHasher), with 600,000 iterations and a per-user salt. Use user.set_password('new') and user.save() to update; never write to user.password directly.

Q: What is the default password hasher iteration count?
A: Since Django 4.1, the default PBKDF2 iterations is 600,000. Tune via the PASSWORD_HASHERS setting. argon2 or bcrypt are recommended alternatives for stronger security.

Q: What is CSRF cookie and how is it named?
A: Django sets the csrftoken cookie (configurable via CSRF_COOKIE_NAME). It is also exposed in the form via {% csrf_token %}. The middleware compares the cookie/submitted token to the value stored in the session.

Q: What is the ALLOWED_HOSTS setting?
A: ALLOWED_HOSTS = ['learncoachassist.com', 'www.learncoachassist.com'] restricts which Host headers Django accepts. In DEBUG=True it defaults to ['localhost', '127.0.0.1', '[::1]'].

Q: What is the SECURE_BROWSER_XSS_FILTER setting?
A: SECURE_BROWSER_XSS_FILTER = True sets the X-XSS-Protection: 1; mode=block response header on older browsers. Modern browsers have deprecated it, but it remains a defense-in-depth measure.

Q: What is SECURE_HSTS_SECONDS?
A: SECURE_HSTS_SECONDS = 31536000 sets the Strict-Transport-Security header for one year, telling browsers to always use HTTPS. Requires SECURE_SSL_REDIRECT = True and HTTPS-enabled infrastructure.

Q: What is SECURE_CONTENT_TYPE_NOSNIFF?
A: SECURE_CONTENT_TYPE_NOSNIFF = True emits the X-Content-Type-Options: nosniff header, preventing browsers from MIME-sniffing a response away from the declared Content-Type.

Q: What does SESSION_COOKIE_AGE control?
A: SESSION_COOKIE_AGE = 1209600 (default 2 weeks) sets the lifetime of the session cookie in seconds. SESSION_EXPIRE_AT_BROWSER_CLOSE = True makes sessions expire when the browser closes.

Q: What is CSRF_COOKIE_HTTPONLY?
A: CSRF_COOKIE_HTTPONLY = True prevents JavaScript from reading the CSRF cookie via document.cookie. The CSRF token is still submitted via form input, so this does not break forms.

Q: What does the LoginRequiredMixin do in CBVs?
A: from django.contrib.auth.mixins import LoginRequiredMixin + class MyView(LoginRequiredMixin, TemplateView) replicates @login_required for class-based views. Override login_url to change the redirect target.

Q: What is UserPassesTestMixin?
A: UserPassesTestMixin calls test_func(); if it returns False, the user is denied. Useful for custom authorization:
class StaffOnly(UserPassesTestMixin):
  def test_func(self):
    return self.request.user.is_staff

Q: What is FormMixin and how is it combined with generic views?
A: FormMixin provides form_class, success_url, and form_valid(). Stack it with generic display views to add form handling:
class ContactFormView(FormMixin, TemplateView):

Q: What is Django's CreateView in detail?
A: CreateView (from django.views.generic.edit) handles the "create new object" flow: GET shows an empty form; POST validates and saves, then redirects to success_url or the new object's absolute URL via get_absolute_url().

Q: What is get_absolute_url() on a model?
A: def get_absolute_url(self):
  return reverse('article-detail', kwargs={'pk': self.pk})
It is used by CreateView and UpdateView for the post-save redirect, and by the {% url %} tag with the model:name convention.

Q: What does UpdateView do?
A: UpdateView fetches an existing object by pk from the URL, populates a ModelForm, and on POST saves the changes. Override form_valid() to add side effects like setting updated_by.

Q: What does DeleteView do?
A: DeleteView shows a confirmation template (default <model>_confirm_delete.html) and on POST deletes the object. Always pair with a POST form; never expose GET-based deletes for security.

Q: What is the ListView paginate_by attribute?
A: class ArticleList(ListView):
  paginate_by = 20
This enables pagination. The view passes page_obj and paginator to the template, and reads the page from the ?page= query parameter.

Q: How do you limit a queryset in ListView?
A: Override get_queryset():
class PublishedList(ListView):
  def get_queryset(self):
    return Article.objects.filter(status='published')
This is preferred over setting queryset directly when you need request-aware filtering.

Q: What is the DetailView slug_url_kwarg?
A: DetailView looks up the object using pk by default. Set slug_url_kwarg = 'slug' and slug_field = 'slug' in Meta so the URL <slug:slug> works as the lookup key.

Q: What is the django.shortcuts module?
A: django.shortcuts provides render(), redirect(), get_object_or_404(), and get_list_or_404(). They keep views short by combining common ORM-and-response patterns.

Q: How does get_object_or_404() differ from get()?
A: get_object_or_404(Article, pk=1) returns the object or raises Http404. Article.objects.get(pk=1) raises DoesNotExist. The shortcut is idiomatic in views because Django's 404 handler renders a friendly page.

Q: What does redirect() return?
A: redirect('view-name', pk=1) returns an HttpResponseRedirect (302) to the resolved URL. You can also pass a model instance with get_absolute_url():
return redirect(article)

Q: What is the HttpResponse object?
A: HttpResponse is the base class for all Django responses. Subclasses include JsonResponse, HttpResponseRedirect, HttpResponseNotFound, and FileResponse. Set status with HttpResponse(status=418).

Q: What is JsonResponse used for?
A: from django.http import JsonResponse
return JsonResponse({'ok': True, 'count': 5})
It sets Content-Type: application/json and serializes the dict with json.dumps. Pass safe=False for non-dict JSON (e.g. lists).

Q: What is FileResponse?
A: FileResponse streams a file-like object to the client without loading it fully into memory:
return FileResponse(open('big.pdf', 'rb'))
It is preferred for large downloads.

Q: What is StreamingHttpResponse?
A: StreamingHttpResponse accepts an iterator (e.g. generator) and streams it to the client chunk by chunk. Useful for CSV exports, SSE, or long-running server responses.

Q: What is the proper way to return a 404 in a view?
A: Use raise Http404("Article not found") or get_object_or_404(Article, pk=pk). Django's 404 handler renders the 404.html template; custom handlers go in handler404 in the root URLconf.

Q: What is the 500 error handler?
A: Define handler500 = 'myapp.views.custom_500' in the root urls.py. The view receives request and returns an HttpResponse. Avoid leaking stack traces — Django only shows them when DEBUG=True.

Q: What is the @require_http_methods decorator?
A: @require_http_methods(['GET', 'POST']) rejects any other method with a 405 Method Not Allowed. @require_GET, @require_POST, and @require_safe are shortcuts for ['GET', 'HEAD'] and ['POST'].

Q: What is the condition decorator?
A: @condition(etag_func=..., last_modified_func=...) enables HTTP conditional GETs. If the client's If-None-Match or If-Modified-Since matches, Django returns 304 Not Modified, saving bandwidth.

Q: What is the never_cache decorator?
A: from django.views.decorators.cache import never_cache ensures the response is not cached by browsers or intermediaries:
@never_cache
def dashboard(request): ...
Useful for personalized or sensitive pages.

Q: What are the @cache_page and cache_control decorators?
A: @cache_page(60 * 15) caches the full view response for 15 minutes. @cache_control(public=True, max_age=3600) sets Cache-Control headers without using Django's cache backend.

Q: What is the per-view cache vs. template fragment cache?
A: @cache_page caches the entire response. {% cache 900 sidebar %}...{% endcache %} caches a template fragment for 15 minutes. Use the fragment cache for partial pages with mixed dynamic content.

Q: How do you configure the cache backend?
A: In settings.py:
CACHES = {
  'default': {
    'BACKEND': 'django.core.cache.backends.redis.RedisCache',
    'LOCATION': 'redis://127.0.0.1:6379/1',
  }
}
Other backends include locmem, db, filebased, and memcached.

Q: What is the low-level cache API?
A: from django.core.cache import cache
cache.set('key', value, timeout=300)
cache.get('key')
cache.get_or_set('key', default, 300)
cache.delete('key')
The default timeout is in seconds; None caches forever.

Q: How do you cache a queryset in Django?
A: Use cache.get_or_set with a string key:
articles = cache.get_or_set(
  'articles:published',
  lambda: list(Article.objects.filter(status='published')),
  300,
)

Q: What is cache invalidation?
A: Removing or replacing a stale cache entry. In Django, common patterns include:
- cache.delete('key') after a save
- Using a versioned key like articles:v1 and bumping the version
- Signals to clear cache automatically on post_save / post_delete

Q: What does the @vary_on_headers decorator do?
A: from django.views.decorators.vary import vary_on_headers
@vary_on_headers('User-Agent', 'Accept-Language') appends those names to the Vary response header, telling shared caches to keep separate copies per header value.

Q: What is the @xframe_options_deny decorator?
A: @xframe_options_deny sets X-Frame-Options: DENY, preventing the page from being embedded in an iframe (clickjacking protection). Variants: xframe_options_sameorigin and xframe_options_exempt.

Q: What is the ClickjackingMiddleware?
A: django.middleware.clickjacking.XFrameOptionsMiddleware sets the X-Frame-Options header on responses that don't define one. Enable via MIDDLEWARE in settings.py.

Q: What is the GZipMiddleware?
A: django.middleware.gzip.GZipMiddleware compresses responses for browsers that send Accept-Encoding: gzip. Avoid compressing already-compressed content (images) — it wastes CPU.

Q: What is ConditionalGetMiddleware?
A: django.middleware.http.ConditionalGetMiddleware handles ETag and Last-Modified automatically. It returns 304 Not Modified when the client already has the latest version, saving bandwidth.

Q: How do you create a custom middleware?
A: A factory function returning a callable that wraps request:
def simple_middleware(get_response):
  def middleware(request):
    response = get_response(request)
    return response
  return middleware
Or subclass MiddlewareMixin for the older style with process_request/process_response.

Q: What is the order of middleware processing?
A: For requests, Django runs middleware top-to-bottom in the MIDDLEWARE list (each calling get_response). For responses, it unwinds in reverse order. Place SecurityMiddleware and SessionMiddleware early so they apply before view logic.

Q: What is the GZipMiddleware order requirement?
A: GZipMiddleware must be near the top of the MIDDLEWARE list so that it compresses content produced by other middlewares and views. Common order:
SecurityMiddleware → SessionMiddleware → GZipMiddleware → ... → CommonMiddleware

Q: How do you write a Django management command that accepts arguments?
A: Use add_arguments(self, parser):
def add_arguments(self, parser):
  parser.add_argument('name', type=str)
  parser.add_argument('--count', type=int, default=1)
Access via self.kwargs['name'] in handle().

Q: How do you use BaseCommand.style()?
A: self.stdout.write(self.style.SUCCESS('Done')) prints in green.
self.style.WARNING('...'), self.style.ERROR('...'), and self.style.NOTICE('...') colorize output. Honors --no-color and --force-color flags.

Q: What is the BaseCommand requires_system_checks flag?
A: Set requires_system_checks = False in a command to skip Django's check framework. Useful for deployment commands where running checks would be redundant.

Q: What is the send_mail() helper?
A: django.core.mail.send_mail(subject, message, from_email, recipient_list) sends a single email via the SMTP backend configured by EMAIL_BACKEND, EMAIL_HOST, EMAIL_PORT, EMAIL_HOST_USER, and EMAIL_HOST_PASSWORD.

Q: What is EmailMessage vs send_mail()?
A: django.core.mail.EmailMessage is a class-based API supporting attachments, HTML, and multiple recipients:
msg = EmailMessage(subject, body, to=['a@example.com'])
msg.attach('report.pdf', pdf_bytes, 'application/pdf')
msg.send()

Q: What is the console email backend?
A: Set EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' to print emails to stdout during development instead of sending them. Use locmem in tests to inspect mail.outbox.

Q: What is the mail.outbox in tests?
A: With EMAIL_BACKEND = 'locmem', Django appends every sent message to django.core.mail.mail.outbox for assertion:
self.assertEqual(len(mail.outbox), 1)
self.assertIn('Welcome', mail.outbox[0].subject)

Q: What is the i18n (internationalization) workflow in Django?
A: 1. Mark strings: from django.utils.translation import gettext_lazy as _ and wrap literals: _('Hello')
2. Run python manage.py makemessages -l hr to extract to locale/hr/LC_MESSAGES/django.po
3. Translate in the .po file
4. Run python manage.py compilemessages to produce .mo files

Q: What is gettext_lazy vs gettext?
A: gettext_lazy returns a lazy proxy that translates when the string is rendered (e.g. in templates), avoiding translation during import. gettext translates immediately. Use gettext_lazy for model fields, app config, and module-level strings.

Q: How do you activate a language per request?
A: Django uses LANGUAGE_CODE by default. django.middleware.locale.LocaleMiddleware selects language from Accept-Language, the session, or a cookie (LANGUAGE_COOKIE_NAME). Set USE_I18N = True in settings.

Q: What is timezone.now() vs datetime.now()?
A: django.utils.timezone.now() returns an aware datetime in USE_TZ=True mode (UTC), while datetime.datetime.now() is naive. Always use timezone.now() in models and views to avoid timezone bugs.

Q: What is auto_now and auto_now_add?
A: created = models.DateTimeField(auto_now_add=True) sets the field once on creation. updated = models.DateTimeField(auto_now=True) updates it on every save. Both default to False for the parameter.

Q: What is the JSONField in Django?
A: models.JSONField() stores arbitrary JSON. On Postgres it uses jsonb; on MySQL 5.7+ and SQLite 3.38+ it uses native JSON. Query with key lookups:
Article.objects.filter(metadata__tags__contains=['python'])

Q: What is a UUIDField?
A: id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
Stores a 128-bit UUID. Pair with a URL converter <uuid:id> for type-safe routing. Useful when you don't want sequential, guessable primary keys.