Django Flashcards
(43 cards)
❓ Q: What is Django and what are its key features?
💡 Answer:
Django is a high-level Python web framework 🛠️
It helps you build websites fast, securely, and with clean code.
It follows two main principles:
- DRY (Don’t Repeat Yourself) 🔁
- MTV (Model – Template – View) 🎭
✨ Key Features of Django
🔄 ORM (Object-Relational Mapping)
Write database queries using Python code — no raw SQL needed!
🛡️ Security Built-in
Guards against XSS, CSRF, SQL Injection, and more 🔐
⚙️ Admin Panel
Auto-generated admin interface for managing data easily 📋
🌐 URL Routing
Control how URLs map to views (in urls.py
) 🧭
🎨 Template Engine
Mix Python and HTML cleanly — keeps logic separate from design 🖌️
📝 Form Handling
Easily validate, clean, and process forms ✉️
🧱 Middleware Support
Add hooks to process requests and responses globally 🔁
🔍 Query API
Write complex queries with simple Python code 📊
🧩 Pluggable Apps
Re-use components like login, blog, cart, etc. — plug and play 🔌
📚 Auto Documentation
Django documents your models — handy for devs and teams 📖
📁 File Uploads
Handle file uploads with built-in utilities 📂
⚡ Async Ready
Supports asynchronous views and tasks (e.g., async APIs) ⚙️
🚀 Scalable
Used by high-traffic websites like Instagram — built to scale 📈
🔗 Versatile
Works with many databases, frontends, and web servers 🌍
🧰 Package Ecosystem
Thousands of plugins on PyPI to extend Django’s power 🧪
🚅 Caching Support
Built-in cache framework to boost performance 🧠💨
🌍 Internationalization
Supports multiple languages — great for global apps 🌐
📡 Django REST Framework
Powerful tool to build RESTful APIs with ease 📲
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
Yeah, so Django is a high-level Python framework that helps you build websites really quickly and securely.
- It follows the DRY principle, so you write less code without repeating yourself, and it uses the MTV architecture — which is similar to MVC but with Django’s flavor: Model, Template, and View.
8 Django comes with a lot of built-in features — like an ORM so you don’t need to write raw SQL, an admin panel that’s auto-generated, form handling, middleware, and really solid security features.
- It’s great for both small projects and big, high-traffic websites — Instagram uses it, for example.
- And thanks to Django REST Framework, it’s also super easy to build APIs.
- It has a huge plugin ecosystem and strong community support.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “Django is a high-level Python web framework that helps you build fast, secure, and clean websites.”
- “It follows DRY and MTV principles.”
- “It has an ORM, admin panel, template engine, and great security.”
- “It works across databases and scales really well.”
- “Django REST Framework makes API development easy.”
- “It has a huge plugin ecosystem and strong community support.”
❓ Q: What is the MTV architecture pattern in Django?
💡 A:
Django follows the MTV (Model - Template - View) pattern 🧩
It’s similar to MVC (Model - View - Controller) but with different naming.
🧱 M – Model
- Represents the data and business logic 📊
- It’s a Python class that maps to a database table
- Example:
class Product(models.Model): ...
🎭 T – Template
- Responsible for the UI and presentation 🎨
- It’s an HTML file with dynamic placeholders (e.g.
{{ product.name }}
) - Shows data to the user 📄
🧠 V – View
- Handles user requests and returns responses 🔁
- Contains the logic of what to do when a URL is accessed
- In Django, it acts more like the Controller in MVC
✅ Summary:
- Model = Data & logic
- Template = Frontend
- View = Logic & control
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
- Yeah, so Django uses the MTV architecture — which stands for Model, Template, and View.
- It’s actually very similar to MVC, but Django just names things a little differently.
- The Model is where you define your data structure and business logic. It’s a Python class that maps directly to a database table.
- The Template handles the frontend — it’s just HTML with dynamic content rendered through placeholders like
{{ product.name }}
. - And the View is where your logic goes. It processes requests and returns responses.
- In fact, Django’s view works kind of like the Controller in the traditional MVC pattern — it decides what happens when a URL is hit.
- So basically:
- The Model talks to the database,
- The Template talks to the user,
- And the View connects them together.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “Django follows the MTV pattern — similar to MVC.”
- “Model = Python class that maps to DB table.”
- “Template = HTML file with placeholders.”
- “View handles logic and acts like a controller.”
- “View returns a response when a URL is accessed.”
- “Model → DB, Template → UI, View → Logic.”
❓ Q: What is a Django project and how is it different from a Django app?
💡 Answer:
- A Django Project is the main container in which you build a web application 🧰
It holds settings, routes, and servers — and can include many apps. - A Django App is a small module 🧩
It handles one specific feature like blog, auth, product, etc.
🏗️ Key Components of a Django Project:
- ⚙️ Settings: Project configurations
- 🌐 URLs: Defines the endpoint mappings using
urls.py
- 🚪 WSGI/ASGI: Entry points for the web server to serve the project, handling HTTP and WebSocket requests, respectively
🧩 Key Components of a Django App:
- 🗃️ Models: Data layer, defining data structures using
models.py
- 🧠 Views: Business logic and presentation layer
- 🎨 Templates: Part of the presentation layer, used for housing HTML and rendering logic
- 📍 URLs: Endpoint mappings for the app, known as “scoped URLs”
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
Yeah, so in Django, a project is like the overall container for your web application.
- It includes all the global stuff — like settings, URL routing, and the server config — and then you plug in different apps that handle specific features.
- Each App is like a reusable component that focuses on one thing — like authentication, blog, or product management.
- Inside an app, you have models, views, templates, and its own scoped URLs — so everything is modular and easy to maintain.
- I usually think of it like this:
- The project sets the stage,
- and the apps are the actors doing different jobs.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “A project is the main container that holds the entire application.”
- “A Django app is a small module for a specific feature.”
- “Project contains settings, URLs, WSGI/ASGI.”
- “App contains models, views, templates, URLs.”
- “Templates are used for rendering HTML and separating logic from design.”
- “Scoped URLs allow each app to manage its own routes.”
❓ Q: Describe the purpose of the settings.py
file in a Django project.
💡 Answer:
The settings.py
file is the main configuration file ⚙️ for a Django project.
It controls how the project behaves, what it connects to, and how it runs.
It allows customization and control over apps, middleware, databases, security, and more.
✨ Key Features of settings.py
:
- ⚙️ Global Settings: Project-wide setup (apps, middleware, URLs…)
- 🔐 Dynamic Configuration: Uses environment variables for dev/staging/prod
- 🛡️ Security & Debugging: CSRF, sessions, error handling
- 🗄️ Database Setup: Connects to SQLite, MySQL, PostgreSQL, etc.
- 🌍 Internationalization: Multi-language support
- 🧩 Customization: Extending features with
AppConfig
or 3rd-party apps
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
Yeah, so settings.py
is basically the control center for your Django project.
* It tells Django what to connect to, how to behave in different environments, and what features to enable or disable.
- It includes global stuff like installed apps, middleware, URL settings, and database configuration — and you can customize it with environment variables so you can easily switch between dev, staging, and production.
- It also handles important things like security settings (e.g., CSRF, session config), error handling, and even internationalization if your app needs to support multiple languages.
- You can also use it to plug in third-party apps and customize behavior using
AppConfig
.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “
settings.py
is the main config file for a Django project.” - “It controls behavior, environment setup, and third-party integrations.”
- “You can use environment variables for flexible setup.”
- “It connects to databases and manages security settings.”
- “Used to extend features with AppConfig or plugins.”
❓ Q: What is the role of the urls.py
file in a Django project?
💡 Answer:
The urls.py
file is used for routing and mapping URLs 🌐 to views.
Each Django project and app can have its own urls.py
for modular URL handling 🧩
🧭 Global URLs vs. App URLs
- 📂 Global (
project.urls
):
Handles the main routing of the whole project — links to each app. - 📦 Local (
app.urls
):
Each app defines its own URL routes for its views.
🔗 URL Patterns in urls.py
- ✅
path()
— for simple, readable URLs (e.g.,/home/
) - 🔢
re_path()
— for complex patterns using regular expressions
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
Yeah, so in Django, the urls.py
file is used to map incoming URLs to the correct view functions or classes.
- There’s a global one — usually in the project folder — that handles the overall routing of the entire app, and then each app can have its own local
urls.py
to keep things modular and organized. - Mostly I use
path()
for clean, readable URLs like/about/
, andre_path()
if I need more control like regex patterns. - I usually split URLs across apps and include them in the main project’s
urls.py
usinginclude()
— it makes the project much easier to scale and manage.
❓ Q: Explain the concept of Django’s ORM (Object-Relational Mapping).
💡 Answer:
Django’s ORM helps you work with relational databases using Python code, not raw SQL 💻📊
It converts Python classes into database tables, and Python objects into records.
🔧 Core Components:
- 🧱 Models
Defined inmodels.py
, represent database tables (as Python classes). - 📦 Model Instances
Objects created from models — represent individual records. - 🔍 QuerySets
Smart queries that let you filter, sort, update data using Python.
🧠 Key Concepts:
- 🧬 Model Classes: Subclass of
django.db.models.Model
, defines table structure - 🧩 Field Types: Use
CharField
,IntegerField
,ForeignKey
, etc. - 🔗 Model Relationships: One-to-many, many-to-many, etc.
- ⚙️ Manager Methods: Use
objects
to access/query the database - 🛠️ QuerySet Methods: Use
.filter()
,.exclude()
,.order_by()
onobjects
🚀 Benefits of Using ORM:
- 🔄 Portability & Flexibility: Works with different DBs (SQLite, PostgreSQL…)
- 🛡️ Security: Prevents SQL injection
- ⚡ Productivity: No need to write raw SQL = faster dev speed
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
Yeah, so Django’s ORM lets you interact with your database using Python instead of raw SQL.
- You define your tables as Python classes in
models.py
, and Django handles the mapping between the class and the table behind the scenes. - Each instance of a model represents a single record, and you can create, update, or delete records using high-level methods like
.save()
or.delete()
. - You also get
QuerySet
s, which are super powerful — you can filter, sort, and even chain them like.filter(...).order_by(...)
, all using Python. - One of the best things is that it’s database-agnostic. So whether you’re using SQLite locally or PostgreSQL in production, your code doesn’t need to change much.
- Plus, since it escapes everything properly, you don’t have to worry about SQL injection.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “ORM converts Python classes into database tables.”
- “Model instances represent individual records.”
- “You use
objects
to access or query the database.” - “
QuerySet
s allow filtering and sorting using Python methods.” - “ORM works with many DB engines and helps avoid SQL injection.”
❓ Q: What is a Django model and how is it defined?
💡 Answer:
A Django Model is a Python class that defines the structure of a database table 🧱
It holds fields, data types, and behaviors for each record in the table.
It must inherit from:
django.db.models.Model
🧱 Key Model Components
🔹 Fields
- 📌 Definition: Table columns
- 🧩 Types:
CharField
,DateField
, etc. - 🔑 Primary Key: Default is
id
, but can be custom - ⚙️ Descriptors: Extra options like
null
,blank
🧰 Meta Options
- 🏷️
table_name
: Set the actual DB table name - 🔗
unique_together
: Force multiple fields to be unique as a group - 🔃
ordering
: Default sorting for queries
🔧 Methods
- 🧠
objects
: Custom model managers - 🗣️
\_\_str\_\_()
: Human-readable name for admin or display
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
🔹 Fields (Diễn giải)
Yeah, so in Django, fields are just the way we define table columns in our models.
* You pick a field type like CharField
or DateField
depending on what kind of data you want to store.
* By default, Django adds an id
field as the primary key, but you can totally set a custom one if needed.
* You also have some extra options — like null
and blank
— that control if a field can be empty in the database or in a form.
So overall, fields handle both the data type and how strict you want it to be when saving or validating.
🔑 Câu nên nhớ:
- “Fields are just the way we define table columns in our models.”
- “By default, Django adds an
id
field as the primary key.” - “You can set a custom primary key if needed.”
- “
null
andblank
let you control if a field can be empty in DB or forms.”
🧰 Meta Options (Diễn giải)
In Django models, you can use a special inner class called Meta
to customize how the model behaves at the database level.
* For example, with table_name
, you can set the actual name of the table in the DB — useful when you want to avoid Django’s default naming.
* unique_together
is handy when you want a combination of fields to be unique together — like, say, no two users can have the same (email, date) pair.
* And ordering
lets you define the default sorting when you query the model — so you don’t have to add .order_by()
every time.
🔑 Câu nên nhớ:
- “Meta is an inner class to control DB behavior of a model.”
- “
unique_together
forces a combination of fields to be unique.” - “
ordering
sets default sorting for queries.”
🔧 Methods (Diễn giải)
-
objects
is the default model manager, but we can override it to customize how we query things. - And of course,
\_\_str\_\_()
is for making the model print nicely — especially useful in the Django admin or when debugging.
🔑 Câu nên nhớ:
- “
objects
is the default model manager.” - “
\_\_str\_\_()
gives a human-readable name — useful for admin and debugging.”
❓ Q: Describe the purpose of Django’s admin interface.
💡 Answer:
The Django Admin Interface is an auto-generated UI ⚙️🖥️
It helps developers create, read, update, and delete (CRUD) model data with minimal setup.
✨ Key Features:
- ⚡ Quick Setup: Works out-of-the-box
- 🧩 Model-Centric: Based on your defined models
- 🔁 DRY Principle: Changes to your models are automatically reflected in the admin interface
🔧 Common Admin Actions:
- 📄 Database Records: View, add, edit, delete
- 🔗 Data Relationships: Navigate through foreign key and many-to-many relationships
- ✅ Validation: Basic field validation built-in
✅ When to Use
- 🚀 Rapid Prototyping: Build fast, test ideas
- 🧪 Internal Tools: Admin-only use
- 🛠️ Quick Fixes: Debugging, small changes
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
- Yeah, so Django comes with a built-in admin interface that’s automatically generated based on your models.
- It gives you a full UI to create, read, update, and delete records — without writing any extra code.
- It’s super useful for developers because it works out-of-the-box — once you register a model, you can manage its data right away.
- The best part is, it follows the DRY principle. So whenever you update your model — like adding or changing fields — the admin reflects that change automatically.
- You can also navigate related data through foreign key or many-to-many relationships, and it handles basic validation for you too.
- I usually use it for quick testing, internal tools, or when I just need to fix something directly in the database during development.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “Django comes with a built-in admin interface that’s automatically generated based on your models.”
- “It lets you create, read, update, and delete records without extra code.”
- “It works out-of-the-box — just register your model and you’re good to go.”
- “It follows the DRY principle — changes to models are reflected in the admin.”
- “Great for quick testing, debugging, or building internal tools fast.”
❓ Q: What is a Django view and how is it created?
💡 Answer:
A Django view is an endpoint 🧭 that handles a web request and returns a response.
- It gets data from the database, processes it 🧠, and returns a response such as:
- 🖼️ HTML page
- 🔄 Redirect
- 📦 JSON data
- Or other content types
👀 Types of Views
- 🔧 Function-Based Views (FBV): Built using Python functions
- 🏗️ Class-Based Views (CBV): Built using Python classes, offering structure, method handling, and mixins
🛠️ Steps to Create a Django View
-
🧠 Define the View Function or Class
- Use a function with a decorator (FBV), or
- Use a class with methods like
get()
,post()
(CBV)
-
🌐 Map the View to a URL
- Add it to
urls.py
usingpath()
orre_path()
- Example:
path('home/', views.home_view)
- Add it to
-
📤 Handle the Request & Return a Response
-
Process input, then return:
- HTML (via template)
- Redirect
- JSON (
JsonResponse
) - Or custom output
-
Process input, then return:
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
Yeah, so in Django, a view is basically an endpoint that receives a request and returns a response.
- It can pull data from the database, process it, and then return things like an HTML page, a redirect, or a JSON response — depending on what you want to build.
- There are two main types: function-based views, which are simple Python functions, and class-based views, which use classes so you can structure logic better — especially when you deal with different HTTP methods like
GET
orPOST
. - To create a view, you define the function or class, map it to a URL in
urls.py
, and then handle the logic inside — like pulling data or returning a response. - I usually start with FBVs for quick things, and switch to CBVs when I need more flexibility.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “A Django view is an endpoint that handles a request and returns a response.”
- “It gets data from the database and returns HTML, JSON, or other responses.”
- “You define the view and map it to a URL using
path()
.” - “Function-based views are simple; class-based views give more structure.”
- “I use FBVs for quick stuff, CBVs when I need reusable logic.”
❓ Q: What is a database migration in Django and why is it important?
💡 Answer:
A database migration is a change to the database schema 🛠️
It keeps the database in sync with your Django models.
Each migration is a Python file that uses django.db.migrations
📄
🧱 Key Components:
- 📂 Migration Files: Define changes to apply to the DB
- 🗃️ Migrations Module: A collection of migration files
- 🧾 Migration Plan: Tracks applied/unapplied migrations
🚀 Why Use Migrations?
- 🗂️ Version Control: Easy to track changes via Git
- ✅ Data Integrity: Keeps schema + data in sync
- 🤝 Collaboration: Teams can share schema changes
- 🔧 Adaptability: Works across DB engines (PostgreSQL, MySQL…)
⚙️ Basic Migration Commands
- 📌 Initial Migration
python manage.py makemigrations
- ✅ Apply Migrations
python manage.py migrate
- 🔍 View Migration Plan
python manage.py showmigrations
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
Yeah, so in Django, a database migration is just a way to keep your database schema in sync with the models you’ve defined in code.
- Whenever you make changes to a model — like adding a new field — Django helps you generate a migration file that knows what changed and how to apply it.
- These migration files are just Python code using
django.db.migrations
, and Django keeps track of which ones have been applied. - You can run
makemigrations
to create them, andmigrate
to apply them to the database. - I really like migrations because they work across different databases, and it’s easy to commit them with your code so the whole team stays synced.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “A migration is a change to the database schema.”
- “It keeps the database in sync with Django models.”
- “Each migration is a Python file using
django.db.migrations
.” - “
makemigrations
creates;migrate
applies.” - “It works across different DB engines and helps with version control.”
❓ Q: Explain the difference between a ForeignKey
and a ManyToManyField
in Django models.
💡 Answer:
In Django, both ForeignKey
and ManyToManyField
are used to create relationships between models.
🔗 ForeignKey
- 🧭 Type: Many-to-One
- 📌 Use Case: One object links to one record in another table
👉 Example:
A Book
has one Publisher
class Book(models.Model): publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
🔗 ManyToManyField
- 🔁 Type: Many-to-Many
- 📌 Use Case: An object can link to many records, and vice versa
👉 Example:
A Student
can enroll in many Course
s
A Course
can have many Student
s
class Student(models.Model): courses = models.ManyToManyField(Course)
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
Yeah, so in Django, if you want to create relationships between models, you use things like ForeignKey
or ManyToManyField
.
- A
ForeignKey
sets up a many-to-one relationship — for example, aBook
can have onePublisher
, but aPublisher
can have many books. - You define it by linking the related model using
ForeignKey
, and you also set how deletions are handled usingon_delete
. - On the other hand, if the relationship goes both ways — like students and courses — you’d use
ManyToManyField
. - So each
Student
can join multipleCourses
, and eachCourse
can have multipleStudents
. - Django handles the join table automatically behind the scenes, so it’s super convenient.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “
ForeignKey
is for many-to-one relationships.” - “One object links to one record in another model.”
- “
ManyToManyField
is for bidirectional many-to-many links.” - “Use
on_delete
to define what happens when the related object is removed.” - “Django manages the join table automatically for
ManyToManyField
.”
❓ Q: What is a QuerySet in Django and how is it used?
💡 Answer:
A QuerySet is a collection of database queries in Django 🗃️
It lets you retrieve, filter, update, and analyze data using Python — all with lazy evaluation and method chaining.
🔰 QuerySet Basics
- 🆕 Initialization: QuerySets are generated automatically when you interact with a Django model using its Manager
- 🔗 Chaining: Multiple methods can be chained together before the QuerySet is evaluated
- 💤 Lazy Evaluation: QuerySets are only executed when data is required — like when iterating through results or calling methods like
list()
orcount()
- 🚫 Immutability After Evaluation: Once a QuerySet is evaluated, its results cannot be altered — e.g., you can’t add more items to a list after it’s been created
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
Yeah, so a QuerySet in Django is basically a way to define database queries in Python without executing them immediately.
- You can chain methods like
.filter()
,.exclude()
,.order_by()
, and Django builds the query in the background. - And it uses lazy evaluation — that means the database query only runs when you actually need the data, like when you iterate over it or call
.count()
. - After it runs once, the results are fixed — you can’t modify the QuerySet contents afterward.
- This makes it super efficient, especially when you’re building complex queries step by step.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “QuerySet lets you retrieve, filter, update, and analyze data using Python.”
- “Chaining allows combining multiple query methods before execution.”
- “It uses lazy evaluation — only executed when data is needed.”
- “Once evaluated, a QuerySet’s results can’t be altered.”
❓ Q: What is a Django model manager and how is it used?
💡 Answer:
A model manager in Django is a gateway to database operations 🧠🗃️
It lets you query, filter, and manage data using Python logic. Every model has a built-in manager called objects
.
🔰 Manager Basics
- 🧩 Auto-added: Django adds the
objects
manager by default - 🔎 Querying: Use it to run queries like:
Article.objects.filter(published=True)
🔧 Custom Managers
Define custom managers to encapsulate logic or customize default queries.
🧑💻 Example:
class PublishedArticleManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(published=True) class Article(models.Model): objects = models.Manager() # default published = PublishedArticleManager() # custom
Use like:
Article.published.all()
🧵 Chaining Queries
Custom managers return QuerySets — so you can chain:
Article.published.filter(category="News").order_by("-date")
➡️ Shows published news articles, sorted newest first
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
Yeah, so in Django, a model manager is like the access point to interact with the database.
- By default, every model has an
objects
manager, and you use that to run queries like.filter()
or.get()
. - But you can also write your own custom manager if you want to centralize common query logic — like getting only published articles.
- It just overrides the
get_queryset()
method and returns a filtered QuerySet — and since it’s still a QuerySet, you can chain more filters on top. - Makes your code cleaner and your logic reusable across the project.
❓ Q: What is the difference between select_related()
and prefetch_related()
in Django queries?
💡 Answer:
Both select_related()
and prefetch_related()
help optimize queries across related models in Django 🧠⚡
But they differ in how and when they fetch related data.
🔍 Key Differences
🔹 select_related()
- 🔗 Best for OneToOne or ForeignKey
- 🛠️ Uses SQL JOIN to pull related data in one query
- ⚡ Super fast when accessing single related objects
🔸 prefetch_related()
- 🔁 Best for ManyToMany or reverse ForeignKey
- 📦 Runs separate queries, then merges in Python
- 📈 Efficient for loading multiple related objects
📌 When to Use
✅ Use select_related()
if:
- You’re accessing single-object relations like
.author
or.profile
- You want to avoid extra queries for simple joins
✅ Use prefetch_related()
if:
- You’re accessing lists of related objects like
.tags.all()
or.comments
- You’re dealing with many-to-many or reverse ForeignKey relations
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
Yeah, so both select_related()
and prefetch_related()
help you avoid the N+1 query problem in Django.
-
select_related()
is great when you’re following a ForeignKey or OneToOne field, because it uses a JOIN — so you get everything in one query. - But when it’s a ManyToMany or reverse relationship, that won’t work — so
prefetch_related()
runs a second query and connects the results in Python. - So basically, if it’s a single related object, go with
select_related()
. If it’s a list, go withprefetch_related()
.
❓ Q: What is a database transaction in Django?
💡 Answer:
A database transaction lets you group multiple DB operations into one atomic action 💥
It guarantees that either all succeed or all fail, keeping your data safe and consistent.
📊 Transaction Modes in Django
- 🔁 Autocommit
- Every operation is instantly saved
- Not ideal for grouped logic
- 💼 Manual Commit
- You control when to save or rollback
- Requires using
transaction.set_autocommit(False)
- 🔒 Atomic (Most Common)
- Wraps actions in a safe block
- Uses
@transaction.atomic
orwith transaction.atomic():
- Rolls back automatically on errors
✅ Why Use It?
- Crucial for multi-step updates (e.g. placing an order, updating stock, logging history)
- Helps enforce ACID properties for data integrity
- Prevents partial saves or inconsistent states if something goes wrong
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
Yeah, so a transaction in Django is basically a way to make sure a group of DB actions either all happen or none do.
- You’ll usually wrap things in
@transaction.atomic
, which is super helpful when you’re doing multi-step stuff — like saving an order and updating stock. - If anything inside fails, the whole thing rolls back — so your DB stays clean and consistent.
- It’s Django’s way of handling ACID rules behind the scenes without you worrying too much about it.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “Transactions = all-or-nothing for DB actions”
- “Use
@transaction.atomic
for safe, grouped operations” - “Prevents partial updates and keeps data consistent”
- “Supports ACID: Atomicity, Consistency, Isolation, Durability”
❓ Q: What is a Django template and how is it rendered?
💡 Answer:
A Django template is a text file with dynamic placeholders 📝
It combines HTML + Django syntax to render pages that change based on the data passed from views.
🧱 Template Structure
- 🧩 HTML base — your layout or UI
- 🧠 Template Tags —
{% if %}
,{% for %}
,{% block %}
, etc. for control flow - 🪄 Template Variables —
{{ user.name }}
to show data
🎯 How Rendering Works
- 🌍 Client requests a page
- 🧭 URLconf routes to a view function
- 📊 The view gets data (e.g. from DB)
- 🧠 Template engine fills in the template
- 📦 HttpResponse sends the final HTML back
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
So a Django template is basically a regular HTML file with some Django-specific syntax added in.
- You can inject variables using
{{ }}
and run logic like loops and conditionals with{% %}
. - The view handles data fetching, then passes it to the template, which builds the final HTML.
- It’s simple and clean — and even non-devs can tweak it without touching the backend logic.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “Django template = HTML + dynamic content using template syntax”
- “
{{ }}
for variables,{% %}
for logic” - “Templates are rendered by the view using the template engine”
- “Keeps presentation and logic separated”
❓ Q: What is context in Django templates?
💡 Answer:
In Django, context is a Python dictionary 🧠
It carries data from the view to the template, letting templates display dynamic content.
⚙️ How It Works
- 🧠 The view creates context — e.g.
{'user': user, 'posts': posts}
- 📄 The template uses
{{ user }}
,{{ posts }}
to render values - 🧰 Context processors can inject extra data globally (like
request
,user
, etc.)
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
Yeah, so the context in Django is basically a dictionary that holds all the data you want to show in the template.
- In your view, you build it with key-value pairs — like
{'name': 'Alice'}
- Then you pass it to
render()
, and in the template, you can access it using{{ name }}
. - It’s the bridge that connects your backend logic with the frontend display.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “Context = dictionary passed from view to template”
- “Used to render dynamic values via
{{ variable }}
” - “Can include extra data via context processors”
❓ Q: How do you pass data from a view to a template in Django?
💡 Answer:
You pass data to a Django template using a context dictionary 📦
This works through either function-based views (FBVs) or class-based views (CBVs).
🔧 FBV — Using render()
from django.shortcuts import render def my_view(request): context = {'key': 'value'} return render(request, 'template.html', context)
✅ The context
is passed to the template and can be accessed using {{ key }}
🏗️ CBV — Using get_context_data()
from django.views.generic import TemplateView class MyView(TemplateView): template_name = 'template.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['key'] = 'value' return context
✅ You override get_context_data()
to inject custom values into the context.
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
So to pass data to a Django template, you just use a context dictionary — it’s basically key-value pairs that the template can render.
- In FBVs, you pass the context directly into the
render()
function. - ## In CBVs, you override
get_context_data()
to add your custom values.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “Use
context
to pass data to templates” - “
render()
for FBVs —get_context_data()
for CBVs” - “Templates use
{{ key }}
to access context values”
❓ Q: What are Django template tags and filters?
💡 Answer:
Template tags and filters let you add logic and formatting directly in Django templates 💻
They keep templates clean while avoiding raw Python code.
🏷️ Template Tags
- Handle control structures — like loops, conditions, and includes
- Syntax:
{% tag %}
- Common examples:
{% if %}
,{% for %}
,{% block %}
,{% include %}
🧪 Example:
{% for item in items %} {{ item.name }} {% endfor %}
🧼 Filters
- Used to transform or format variables
- Syntax:
{{ variable | filter }}
- Can chain filters with
|
for multiple transformations
🧪 Example:
{{ name | upper | truncatechars:10 }}
→ "JonathanDoe"
→ "JONATHAND…"
, if too long
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
Yeah, so in Django templates, tags and filters let you do logic and formatting right inside the HTML.
- Tags are things like
{% if %}
or{% for %}
— they’re for flow control. - Filters are used to tweak the output — like turning text lowercase or formatting dates using
| lower
or| date
. - It’s great because you can keep your presentation logic inside the template, without mixing in Python.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “Tags = control flow (
{% if %}
,{% for %}
)” - “Filters = format output (
{{ name | upper }}
)” - “Clean separation of logic and presentation in templates”
❓ Q: What is the purpose of the {% block %}
tag in Django templates?
💡 Answer:
The {% block %}
tag is a content placeholder 🧩
It’s key to template inheritance — letting child templates insert custom content into a shared layout.
🏗️ Core Concepts
🧱 Base Template
<!-- base.html --> <html> <body> {% block content %}{% endblock %} </body> </html>
- Defines named blocks (
content
,title
, etc.) - Acts as the layout foundation for other templates
🔁 Child Template
{% extends "base.html" %} {% block content %} <p>This is page-specific content.</p> {% endblock %}
- Uses
{% extends %}
to inherit the layout - Fills in the
{% block %}
with custom content
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
Yeah, so {% block %}
is what makes Django templates reusable.
- You define blocks in a base template — like
block content
— and then child templates can override just those parts. - It’s super helpful for keeping your layout consistent and avoiding duplicate HTML.
- You only change what you need, while the rest stays the same.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “
{% block %}
marks replaceable sections in a template” - “Use with
{% extends %}
for inheritance” - “Promotes DRY — write layout once, reuse everywhere”
❓ Q: What is a Django Form?
💡 Answer:
A Django Form is a class that handles user input, validation, and HTML rendering 📩✅🖼️
It makes it easy to build forms, check data, and display errors — all in Python.
🧩 Core Parts to Remember:
- 📥 Fields – Built-in types like
CharField
,EmailField
,DateField
- ✅ Validation – Includes automatic checks + custom logic via
.clean()
methods - 🖼️ Rendering – Forms can auto-generate HTML
- 🧱 Widgets – Customize input types (
TextInput
,Textarea
, etc.) - 🏷️ Labels & Help Text – Enhance UX and accessibility
- 🔄 Formsets – Manage multiple forms at once (e.g. for dynamic rows)
🧑💻 Tiny Example:
from django import forms class ContactForm(forms.Form): name = forms.CharField() email = forms.EmailField()
This will render a basic form and handle validation out of the box.
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
So a Django Form is just a class that represents a form — it defines the fields, validates input, and even renders the HTML.
- It saves a ton of time because you don’t need to write your own validation logic or HTML manually.
- Plus, it gives you clear errors when something goes wrong and is super customizable with widgets and styling.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “Forms handle input, validation, and rendering”
- “Fields define structure,
.clean()
handles validation” - “Forms can be rendered automatically or customized with widgets”
- “Formsets = multiple forms as a group”
❓ Q: What’s the difference between a function-based view (FBV) and a class-based view (CBV) in Django?
💡 Answer:
Django offers Function-Based Views (FBV) and Class-Based Views (CBV) for building views — both serve the same purpose, but their style and flexibility differ ⚖️
🔹 Function-Based View (FBV)
- 🧠 Just a regular Python function
- ✅ Easy to read & quick to write
- 🔧 You manage the logic manually (like
if request.method == "POST"
) - 👌 Best for simple or one-off views
- 💡 Great when you want full control with minimal abstraction
🔸 Class-Based View (CBV)
- 🏗️ Based on OOP — define a class inheriting from
View
or built-ins - 🔍 Split logic into methods like
.get()
and.post()
- 🔌 Comes with generic views like
ListView
,FormView
,DetailView
- ♻️ Reusable via inheritance and mixins
- 🧱 Ideal for large or DRY-focused codebases
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
FBVs are like raw functions — super clear and simple. You just write a function, check the request method, and return a response.
CBVs are more structured. You create a class, override methods like get()
or post()
, and can use Django’s built-in views to save time.
FBV is great when you want to move fast. CBV is great when you want to scale and reuse code.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “FBV = quick + explicit”
- “CBV = reusable + structured”
- “Use FBV for simplicity, CBV for power and scalability”
❓ Q: What is view inheritance in Django?
💡 Answer:
View inheritance in Django means writing shared logic once in a base view and letting other views inherit it 🧠📦
It helps you follow the DRY principle and organize complex views cleanly.
🔹 How It Works
- 🧱 Base View → defines common behavior (
get()
,post()
, helper methods, etc.) - 🧬 Child View → inherits and can override, extend, or reuse that logic
- 🧭 Django uses child view logic first, falling back to the base as needed
🧑💻 Example:
```python
from django.http import HttpResponse
from django.views import View
class BaseView(View):
def get(self, request):
return HttpResponse(“Base GET response”)
class ChildView(BaseView):
def get(self, request):
base_response = super().get(request)
return HttpResponse(“Child overrides base: “ + base_response.content.decode())
~~~
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
So view inheritance is just like class inheritance in Python — you define shared logic in a base view and reuse it across multiple views.
- For example, if every view in a section needs login checking or a shared context setup, you can put that in a base class.
- Then child views can just extend it, and override what they need.
It’s especially useful when working with class-based views (CBVs).
🔑 Câu nên nhớ (Highlight để học thuộc):
- “BaseView holds shared logic — reusable, extendable”
- “Child views can override or call
super()
” - “Keeps views DRY, clean, and maintainable”
❓ Q: What is Django middleware and how is it used?
💡 Answer:
Middleware is a 🔁 processing layer in Django — it sits between the request and the view, and between the view and the response.
It lets you intercept, modify, or block both requests and responses.
🛠️ What It’s Used For
- 🔐 Authentication & Authorization
- 🧾 Logging & Monitoring
- ⚙️ Custom headers (CORS, Content-Type, etc.)
- 🔁 Redirects or security enforcement
- ⚠️ Error handling or response transformation
📦 How It Works
- Defined in
settings.py
inside theMIDDLEWARE
list - Runs in order:
- ⬇️ Request: Top → Bottom
- ⬆️ Response: Bottom → Top
🧑💻 Example
# settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ... ]
🎙️ Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):
Middleware in Django is like a gatekeeper that can check or modify requests and responses.
- For example, before a request reaches the view, middleware can check if the user is logged in.
- And before sending a response back to the browser, middleware can attach custom headers or log the request.
🔑 Câu nên nhớ (Highlight để học thuộc):
- “Middleware processes requests before views, and responses before they leave”
- “Used for auth, logging, headers, and more”
- “Order in
MIDDLEWARE
list matters — top-down for request, bottom-up for response”