Django Flashcards

(43 cards)

1
Q

❓ Q: What is Django and what are its key features?

A

💡 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.”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

❓ Q: What is the MTV architecture pattern in Django?

A

💡 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.”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Q: What is a Django project and how is it different from a Django app?

A

💡 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.”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Q: Describe the purpose of the settings.py file in a Django project.

A

💡 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.”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Q: What is the role of the urls.py file in a Django project?

A

💡 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/, and re_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 using include() — it makes the project much easier to scale and manage.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Q: Explain the concept of Django’s ORM (Object-Relational Mapping).

A

💡 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:

  1. 🧱 Models
    Defined in models.py, represent database tables (as Python classes).
  2. 📦 Model Instances
    Objects created from models — represent individual records.
  3. 🔍 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() on objects

🚀 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 QuerySets, 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.”
  • QuerySets allow filtering and sorting using Python methods.”
  • “ORM works with many DB engines and helps avoid SQL injection.”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Q: What is a Django model and how is it defined?

A

💡 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 and blank 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.”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Q: Describe the purpose of Django’s admin interface.

A

💡 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 recordswithout writing any extra code.
  • It’s super useful for developers because it works out-of-the-boxonce 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.”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Q: What is a Django view and how is it created?

A

💡 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

  1. 🧠 Define the View Function or Class
    • Use a function with a decorator (FBV), or
    • Use a class with methods like get(), post() (CBV)
  2. 🌐 Map the View to a URL
    • Add it to urls.py using path() or re_path()
    • Example:
      path('home/', views.home_view)
  3. 📤 Handle the Request & Return a Response
    • Process input, then return:
      • HTML (via template)
      • Redirect
      • JSON (JsonResponse)
      • Or custom output

🎙️ 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 or POST.
  • 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.”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Q: What is a database migration in Django and why is it important?

A

💡 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

  1. 📌 Initial Migration
    python manage.py makemigrations
  2. Apply Migrations
    python manage.py migrate
  3. 🔍 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, and migrate 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.”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Q: Explain the difference between a ForeignKey and a ManyToManyField in Django models.

A

💡 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 Courses
A Course can have many Students

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, a Book can have one Publisher, but a Publisher can have many books.
  • You define it by linking the related model using ForeignKey, and you also set how deletions are handled using on_delete.
  • On the other hand, if the relationship goes both ways — like students and courses — you’d use ManyToManyField.
  • So each Student can join multiple Courses, and each Course can have multiple Students.
  • 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.”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Q: What is a QuerySet in Django and how is it used?

A

💡 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() or count()
  • 🚫 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.”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Q: What is a Django model manager and how is it used?

A

💡 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Q: What is the difference between select_related() and prefetch_related() in Django queries?

A

💡 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 with prefetch_related().
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Q: What is a database transaction in Django?

A

💡 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

  1. 🔁 Autocommit
    • Every operation is instantly saved
    • Not ideal for grouped logic
  2. 💼 Manual Commit
    • You control when to save or rollback
    • Requires using transaction.set_autocommit(False)
  3. 🔒 Atomic (Most Common)
    • Wraps actions in a safe block
    • Uses @transaction.atomic or with 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”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Q: What is a Django template and how is it rendered?

A

💡 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

  1. 🌍 Client requests a page
  2. 🧭 URLconf routes to a view function
  3. 📊 The view gets data (e.g. from DB)
  4. 🧠 Template engine fills in the template
  5. 📦 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Q: What is context in Django templates?

A

💡 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

  1. 🧠 The view creates context — e.g. {'user': user, 'posts': posts}
  2. 📄 The template uses {{ user }}, {{ posts }} to render values
  3. 🧰 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”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Q: How do you pass data from a view to a template in Django?

A

💡 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”
19
Q

Q: What are Django template tags and filters?

A

💡 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”
20
Q

Q: What is the purpose of the {% block %} tag in Django templates?

A

💡 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”
21
Q

Q: What is a Django Form?

A

💡 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”
22
Q

Q: What’s the difference between a function-based view (FBV) and a class-based view (CBV) in Django?

A

💡 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”
23
Q

Q: What is view inheritance in Django?

A

💡 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”
24
Q

Q: What is Django middleware and how is it used?

A

💡 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 the MIDDLEWARE 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”
25
❓ **Q: What is CSRF middleware in Django?**
✅ **Answer:** It **protects your website** from fake form submissions (attacks from other websites) by **checking for a secret token** 🔒 --- 🔐 **How it works (simple steps)** 1. Django gives your form a **hidden token** like this: ```html ``` 2. When the form is submitted (POST), Django checks: * “Is this token valid?” * “Did it come from our site?” 3. If the token is **missing or fake** → Django **blocks** the request ❌ --- 🤖 **Why it matters** Without this, a hacker could trick your users into submitting forms **without their knowledge**. --- 🎙️ **Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):** ***Yeah, so CSRF protection in Django is basically a security layer that prevents other websites from submitting forms on your behalf.*** * When you render a form, Django adds a hidden token to it — and then, when the form is submitted, it checks that the token is still there and valid. * That way, only forms from **your** site can be submitted successfully. * If someone tries to fake a request from another site without the token, Django blocks it. *This stops attacks where a user might be tricked into submitting something dangerous — like changing a password without realizing it.* --- 🔑 **Câu nên nhớ (Highlight để học thuộc):** * “CSRF protection checks for a **valid hidden token** in POST forms.” * “It blocks **fake or cross-site submissions**.” * “Only forms from **your domain** will pass the check.”
26
❓ **Q: What is the Django authentication system and how does it work?**
🎙️ **Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):** ***Yeah, Django’s auth system is a built-in way to handle user authentication — things like login, logout, and session tracking.*** * When a user logs in, Django saves their info in a session, and from then on you can just use `request.user` to access that user in any view. * The middleware (`AuthenticationMiddleware`) runs on every request to attach the logged-in user to it. * Django also gives you ready-made views like `login`, `logout`, and `password_change`, but you can override them if you want to customize the flow. * And if you need to integrate with something like Google, LDAP, or SSO, you can plug in your own backend too. *It’s flexible, secure, and saves a ton of dev time since most of the hard parts are already done for you.* --- 🔑 **Câu nên nhớ (Highlight để học thuộc):** * “Django auth handles **login/logout/session** management out of the box.” * “`request.user` gives access to the current logged-in user.” * “`AuthenticationMiddleware` links the session to the request.” * “You can customize the **user model, views**, or **auth backends**.”
27
❓**Q: What's the difference between authentication and authorization?**
🎙️ **Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):** ***Yeah, so authentication is about verifying **who** the user is — like when they log in with a username and password. Once that's done, Django sets `request.user`, and you know who's using the app.*** *Then comes authorization — that’s about checking if that user is **allowed** to do something, like access a view or perform an action.* * You can use decorators like `@login_required` to make sure the user is logged in, or `@permission_required` if you want to check for specific permissions. *So the flow is: first we check **who you are** (authentication), then we check **what you can do** (authorization).* --- 🔑 **Câu nên nhớ (Highlight để học thuộc):** * “**Authentication**: confirms identity → `authenticate()` + `login()`.” * “**Authorization**: checks access → `@login_required`, permissions.” * “You must be **authenticated before authorized**.” * “`request.user` holds the logged-in user after authentication.”
28
❓**Q: How do you create a custom user model in Django?**
🎙️ **Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):** ***Yeah, if you want to customize the user model in Django — like adding extra fields or changing how users log in — you usually subclass `AbstractUser` or `AbstractBaseUser`.*** * `AbstractUser` is easier because it gives you all the default fields and behavior (username, email, etc.), and you just add to it. * `AbstractBaseUser` is more flexible — you build the whole user model from scratch, including fields and manager logic — but it's more work. *Either way, you define your custom user early (before migrations) and set it using `AUTH_USER_MODEL` in `settings.py`.* --- 🔑 **Câu nên nhớ (Highlight để học thuộc):** * “Use `AbstractUser` to extend the default user model easily.” * “Use `AbstractBaseUser` for full customization (email login, etc.).” * “Set `AUTH_USER_MODEL` in settings before migrating.”
29
❓ What is a session in Django?
🎙️ **Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):** ***Yeah, so a session in Django is basically how the server keeps track of a user's state between requests — like whether they’re logged in or what’s in their cart.*** * Behind the scenes, Django stores a session ID in the user’s browser via a cookie, and maps that to session data on the server — usually in the database. * You can store stuff in `request.session` just like a Python dictionary, and it sticks around until the user logs out or the session expires. * You can even choose where to store session data — database, cache, or files — by changing `SESSION_ENGINE`. --- 🔑 **Câu nên nhớ (Highlight để học thuộc):** * “Session stores user-specific data **between requests**.” * “Django saves session data on the server, and links it with a cookie on the client.” * “You interact with it using `request.session['key'] = value`.” * “Storage and expiry are customizable via settings.”
30
❓ **Q: What are user groups and permissions in Django?**
💡 **Answer:** User groups and permissions help manage access control in Django. You can assign permissions to individual users or groups. Groups let you apply the same permissions to many users at once. There are two main types: * **Boolean permissions** like `can_add`, `can_change`, `can_delete`, `can_view` * **Custom permissions** defined in the model’s `Meta` class Permissions can be: * **User-Centric:** Assigned directly to users * **Group-Centric:** Inherited from the user’s groups --- 🎙️ **Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):** **Groups and permissions in Django are like a built-in system to control who can do what.** * You can assign permissions directly to users, but when you have a team (say, all editors), it’s better to put them in a group and assign permissions to that group. It makes management way easier. * For example, a user might have `can_view` and `can_change` on an article model — that controls whether they can see and edit content. * You can also define your own custom permissions if your app needs something more specific, like `can_publish`. --- 🔑 **Câu nên nhớ (Highlight để học thuộc):** * “Groups are for reusing permissions across many users” * “Use built-in permissions or define custom ones in the model” * “Direct = user-based, Reusable = group-based”
31
❓ **Q: What’s the difference between unit tests and integration tests in Django?**
💡 **Answer:** Unit tests in Django check individual components (like models, views, or forms) in isolation. They're fast and useful during development to catch bugs early. Integration tests verify how different parts of the system work together, like templates, views, and database connections. They simulate full workflows to ensure everything integrates correctly. Django provides `unittest` for both types and `LiveServerTestCase` for full-stack integration testing with a live server.
32
❓ **Q: What is a fixture in Pytest?**
💡 **Answer:** A **fixture** in **Pytest** is a **reusable function** that provides setup (and optional teardown) code for your tests. Fixtures help prepare test dependencies such as database connections, test data, mock objects, or configs — **automatically injected** into test functions by name. 🔁 Fixture Scope: * `function` (default): runs before each test. * `class`: runs once per class. * `module`: runs once per module. * `session`: runs once per testing session. ✅ **Pytest fixtures** improve **code reuse**, **separation of concerns**, and **readability** in test suites. --- 🎙️ **Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):** **Pytest fixtures are like smart helpers that set up what your test needs — before the test even runs.** * For example, if a test needs a database connection or some mock data, you can create a fixture that sets that up. Pytest will automatically pass it into your test function — just by matching the name. * The cool part? You don’t have to call the fixture — Pytest sees the parameter and injects it for you. * You can also control how often a fixture runs: once per test (`function`), or only once for the whole session (`session`) if it’s expensive to set up. --- 🔑 **Câu nên nhớ (Highlight để học thuộc):** * “Fixtures = reusable setup code, injected by name” * “Improves test **clarity**, **reuse**, and **modularity**” * “Fixture scope controls **how often** it runs: function, class, module, session”
33
❓ **Q: What is the Django Debug Toolbar and how is it used?**
💡 **Answer:** The **Django Debug Toolbar** is a powerful development tool that helps developers **inspect, debug, and optimize** their Django applications during development. --- 🔍 Key Features: * **Request/Response Inspection**: See request headers, response content, and redirection data. * **SQL Queries**: View executed SQL queries, time taken, and duplicate queries. * **Template Rendering**: Check which templates were used and how long they took. * **Cache Usage**: Monitor cache hits/misses. * **Logging**: Track custom log output from your app. * **Signals**: See what Django signals were triggered and in what order. --- ✅ **Usage**: Install it with `pip install django-debug-toolbar`, add `'debug_toolbar'` to `INSTALLED_APPS`, configure middleware, and include its URL in `urls.py` (only in `DEBUG=True` mode).
34
❓ **Q: How do you handle exceptions and errors in Django views?**
💡 **Answer:** In Django, you handle exceptions at three levels: **middleware**, **views**, and **form fields**. --- 🛡️ **Middleware** * Use `ExceptionMiddleware` and the `process_exception(request, exception)` method to catch all exceptions **before** they reach views. --- 🧠 **Views** **Function-Based Views:** Use decorators like: ``` @require_http_methods(["GET", "POST"]) ``` **Class-Based Views:** Override HTTP methods (`get`, `post`, etc.): ``` def get(self, request): return HttpResponse(status=400) # e.g., bad request ``` --- 📝 **Form Validations** Use `clean()` and raise `ValidationError`: ``` if age < 18: raise ValidationError("Age should be 18 or above") ``` --- ⚠️ **Built-in HTTP Error Responses** * `HttpResponseBadRequest(status=400)` * `HttpResponseServerError(status=500)` * `HttpResponseNotFound(status=404)` * `HttpResponseForbidden(status=403)` * `HttpResponseNotAllowed(status=405)` Django also includes `Http404` and `PermissionDenied` for clearer semantics. --- 🎙️ **Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):** **In Django, exception handling is flexible — you can catch errors globally or handle them where they happen.** * If you want to catch *everything* app-wide, use middleware. It’s like a safety net that can log or transform exceptions before they hit your views. * In views, you can return custom error responses — like returning a 400 or 403 if something’s off in the request. * And in forms, validations are super clean — you just raise a `ValidationError` inside the `clean()` method. * Django even gives you shortcuts like `Http404` or `PermissionDenied` so your code stays expressive and readable. --- 🔑 **Câu nên nhớ (Highlight để học thuộc):** * “3 levels: middleware → views → forms” * “Use middleware for global handling, views for logic-based responses” * “Raise `ValidationError`, `Http404`, or use built-in `HttpResponse...` types”
35
❓ **Q: What is the difference between the `DEBUG` and `ALLOWED_HOSTS` settings in Django?**
💡 **Answer:** Both `DEBUG` and `ALLOWED_HOSTS` are critical for Django’s **security** and **deployment**. --- 🐞 **`DEBUG`** * Enables detailed error pages and auto-reload in **development** mode. * Set in `settings.py`: ``` DEBUG = True ``` * ❗ **Never set `DEBUG = True` in production**, as it may expose sensitive info. --- 🌐 **`ALLOWED_HOSTS`** * Defines a list of allowed domain names/IPs that your Django app can serve. * Protects against: * **Host header attacks** * **Cache poisoning** * **Clickjacking** Example: ``` ALLOWED_HOSTS = ['example.com'] ``` * In **production**, always set `DEBUG = False` and configure `ALLOWED_HOSTS` properly. --- 🎙️ **Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):** **`DEBUG` and `ALLOWED_HOSTS` are two small settings in Django — but they have huge security implications.** * `DEBUG = True` is great while developing — it shows you full error tracebacks, auto-reloads the server, and gives a lot of feedback. But in production, it’s dangerous because it might leak sensitive data. * On the other hand, `ALLOWED_HOSTS` is like a security filter. Django will only serve requests from the domains you list there. If someone tries to spoof the Host header, Django will block it. * So in production, it’s a must to turn off `DEBUG` and define your `ALLOWED_HOSTS` properly — they go hand-in-hand for keeping your app secure. --- 🔑 **Câu nên nhớ (Highlight để học thuộc):** * “`DEBUG = True` shows error details — great for dev, risky in prod” * “`ALLOWED_HOSTS` whitelists domains — protects against spoofing” * “In production: `DEBUG = False` + proper `ALLOWED_HOSTS`”
36
❓ **Q: What are the steps involved in deploying a Django application?**
💡 **Answer:** Deploying a Django application involves several steps to ensure stability, scalability, and security: --- ✅ Deployment Checklist 1. **Set up Virtual Environment** Use `venv` or `virtualenv` to isolate dependencies. 2. **Use Version Control** Manage code with Git to allow rollback and collaboration. 3. **Choose a Production Web Server** Use Nginx, Apache, or Gunicorn instead of Django's dev server. 4. **Configure Production Settings** * `DEBUG = False` * Set `ALLOWED_HOSTS` * Add secure headers 5. **Connect to a Production-Grade Database** Configure PostgreSQL or MySQL in `settings.py`. 6. **Automate with Fabric or Ansible** Automate deployment, server config, and backups. 7. **Use a WSGI Server** Serve Django via Gunicorn or uWSGI for better performance. 8. **CDN for Static/Media Files** Offload static files to S3, Cloudflare, etc. 9. **Add SSL (HTTPS)** Install certificates (e.g., Let’s Encrypt) and force HTTPS. 10. **Enable Error Logging** Configure Django `LOGGING` and web server logs. 11. **Harden Security** * Enable security middleware * Use `SECURE_*` settings * Follow OWASP guidelines 12. **Add Monitoring** Use tools like Sentry, Prometheus, or uptime monitors.
37
❓ **Q: What is WSGI (Web Server Gateway Interface) in Django deployment?**
Dưới đây là phần 🎙️ **Interview-Friendly Casual Explanation** cho chủ đề **WSGI in Django**, đúng format bạn yêu cầu: --- 💡 **Answer:** WSGI is a specification that allows web servers (like Nginx or Gunicorn) to communicate with Python web applications, including Django. --- 🔧 **How It Works** * The **web server** receives an HTTP request and passes it to Django via WSGI. * Django processes the request and returns an HTTP response. * The **WSGI server** (e.g., Gunicorn) acts as the bridge between them. --- 🧠 **Core Concepts** * **WSGI Server**: Handles the server-side communication and runs Django apps. * **Django’s `wsgi.py`**: Exposes the `application` object used by WSGI servers. ```python # wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') application = get_wsgi_application() ``` --- ✅ **Why WSGI Matters** * **Portability**: Run your Django app on any WSGI-compliant server. * **Compatibility**: Works across multiple web servers and deployment tools. * **Concurrency**: Supports multiple threads or processes for scalability. --- 🎙️ **Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):** **Think of WSGI as the translator between your Django app and the outside world.** * When a user makes a request, the web server (like Nginx) doesn’t talk to Django directly — it passes the request to a WSGI server like Gunicorn. * Gunicorn knows how to speak both HTTP and Python. It takes the request, hands it off to Django (through the `wsgi.py` entry point), and then sends Django’s response back to the user. * This standard interface makes your Django app portable — it can run on any server that understands WSGI. --- 🔑 **Câu nên nhớ (Highlight để học thuộc):** * “WSGI = bridge between web server and Django app” * “Gunicorn handles HTTP → Django via `wsgi.py`” * “WSGI makes Django apps portable, scalable, and server-friendly”
38
❓ **Q: How do you handle static files in a Django production environment?**
💡 **Answer:** In production, Django doesn't serve static files by default. Instead, you use dedicated tools or configurations to serve them efficiently and securely. --- 🧰 **Common Approaches** 1. **WhiteNoise** * Lightweight, works well with WSGI servers (like Gunicorn). * Handles compression, caching, and cache-busting. * Great for simple deployments (e.g., Heroku). 2. **ManifestStaticFilesStorage** * Renames files with content hashes (e.g., `style.abcd1234.css`). * Prevents browsers from using stale versions. * Good when you want long-term caching. 3. **Web Servers (NGINX or Apache)** * Serve static files directly — super fast and efficient. * Frees Django from that job. * Ideal for production or high-traffic setups. --- 📦 **Don’t forget to run:** ``` python manage.py collectstatic ``` * This command gathers all static files into one folder (`STATIC_ROOT`) for serving. --- 🎙️ **Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):** **In production, Django steps aside when it comes to static files — it lets other tools handle that more efficiently.** * You can use **WhiteNoise** if you want a quick, straightforward solution that works well with Gunicorn — perfect for small projects or platforms like Heroku. * For better caching, Django offers **ManifestStaticFilesStorage**, which renames files with unique hashes so browsers always get the right version. * But the best performance comes from using a real web server like **NGINX** — it can serve static files way faster than Django ever could. And don’t forget — before deploying, you have to run `collectstatic` so Django knows where to gather and serve everything from. --- 🔑 **Câu nên nhớ (Highlight để học thuộc):** * “Django **doesn’t serve static files** in production — use WhiteNoise or NGINX” * “Run `collectstatic` to gather all static assets” * “Use **ManifestStaticFilesStorage** for cache-friendly filenames”
39
❓ **Q: What is Django caching and how is it implemented?**
💡 **Answer:** Django caching improves performance by storing frequently accessed data, avoiding repeated computation or DB access. It works at multiple levels and supports different backends like Memcached, Redis, or filesystem. --- 🔧 **Core Components** * **Cache Backends**: Memory (`locmem`), DB, file system, Memcached, Redis. * **Cache Decorators**: Cache entire views or function outputs easily. * **Cache API**: Manually `cache.set()`, `cache.get()` data as needed in code. --- 🧱 **Caching Layers** 1. **Query Caching** – Cache ORM results to reduce DB hits. 2. **Template Fragment Caching** – Cache parts of a template (e.g., sidebar, navbar). 3. **View Caching** – Cache entire views using `@cache_page`. 4. **Low-Level API** – Direct access to the cache (`cache.set()`, `cache.get()`). 5. **HTTP Caching** – Use headers like `Cache-Control`, `ETag` for browser/proxy-level caching. --- 🎙️ **Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):** **Caching in Django is like putting frequently used results into a “shortcut memory” so your app doesn't have to redo the same work.** * For example, if you have a view that fetches data from the database and formats a big page — you can use `@cache_page` so Django just stores the final result and skips recomputing it next time. * You can also cache just part of a template — like a sidebar or expensive query block — using **template fragment caching**. * And behind the scenes, Django can use **Redis**, **Memcached**, or even simple file-based caches to store that data. * If you need more control, Django gives you low-level APIs like `cache.get()` and `cache.set()` to manage data manually. --- 🔑 **Câu nên nhớ (Highlight để học thuộc):** * “Django cache = speed boost by avoiding redundant work” * “Use `@cache_page` for full views, fragment cache for templates” * “Backends like Redis/Memcached handle the storage” * “Don’t forget: you can also use headers for HTTP-level caching”
40
❓ **Q: What is load balancing in Django deployment?**
💡 **Answer:** Load balancing distributes incoming traffic across multiple Django servers to improve scalability, fault tolerance, and performance. --- ⚙️ **Benefits** * **Scalability**: Add more servers to handle increased traffic. * **Fault Tolerance**: If one server fails, others take over. * **Performance**: Requests are spread out, reducing latency. --- 🔁 **Common Algorithms** * **Round Robin** – Sends each request to the next server in a loop. * **Least Connections** – Picks the server with the fewest active connections. * **IP Hash** – Keeps requests from the same client going to the same server (sticky sessions). --- 🧱 **Typical Setup** 1. **Deploy multiple Django servers** behind a load balancer. 2. Use **NGINX** or **Apache** as a **reverse proxy**. 3. Use **HAProxy** or **NGINX** to distribute traffic. 4. Ensure all servers are on the **same network** and serve the same app. --- 🎙️ **Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):** **Load balancing is like putting a traffic officer in front of your Django servers — making sure no one server gets overwhelmed.** * Imagine your app gets a ton of traffic. Instead of having one Django server handle everything (and possibly crash), you can spin up multiple servers. * Then you put a tool like **NGINX** or **HAProxy** in front, and it decides where each request goes — spreading them out evenly. * This setup boosts performance and keeps things running smoothly even if one server has issues. * Plus, depending on the algorithm (like Round Robin or Least Connections), the load balancer can decide how to distribute traffic smartly. --- 🔑 **Câu nên nhớ (Highlight để học thuộc):** * “Load balancing = distributing requests across multiple servers” * “Improves **scalability**, **fault tolerance**, and **performance**” * “NGINX or HAProxy = common tools used as load balancers” * “Algorithms: Round Robin, Least Connections, IP Hash (sticky sessions)”
41
❓ **Q: What is database connection pooling in Django?**
💡 **Answer:** Database connection pooling is a technique that boosts performance by reusing existing database connections instead of creating a new one for every request. This reduces overhead and improves resource management. --- ⚙️ **How It Works** 1. **Reuses Connections** – Already-open connections are recycled instead of reopened. 2. **Handles Concurrency** – Each request gets a managed connection, even under high load. --- 🚀 **Benefits** * **Speed**: Faster than opening new connections each time. * **Efficiency**: Reduces load on web and database servers. * **Scalability**: Better suited for high-traffic environments. --- 🎙️ **Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):** **Connection pooling is like keeping a pool of open database connections ready to go — instead of making a fresh one every time a user visits your site.** * Without pooling, Django opens and closes a database connection for every single request — that’s expensive and slow. * With pooling, once a connection is created, it goes back into the “pool” and can be reused by the next request. * This means faster response times and less pressure on both your Django app and the database. * It’s especially useful in high-traffic environments where performance matters. In Django, you can enable pooling by using external libraries like **`pgbouncer`** (PostgreSQL) or **connection pooling backends** such as `django-db-geventpool` or `SQLAlchemy` with custom setup. --- 🔑 **Câu nên nhớ (Highlight để học thuộc):** * “Connection pooling = reuse existing DB connections for performance” * “Faster, more efficient, and scalable under load” * “Tools like **pgbouncer** or **django-db-geventpool** can enable it”
42
❓ **Q: How do you optimize Django database queries for better performance?**
💡 **Answer:** To optimize Django database queries, use smart query methods like `select_related()`, `prefetch_related()`, `defer()`, and `only()` to reduce unnecessary database hits and load only the needed data. --- 🔁 `select_related()` (for ForeignKey, One-to-One) * Joins related objects in the **same query** (SQL JOIN). ```python books = Book.objects.select_related('author') ``` --- 📥 `prefetch_related()` (for Many-to-Many, reverse FK) * Runs a **separate query**, joins in **Python memory**. ```python blog = Blog.objects.prefetch_related('tags').get(id=1) tags = blog.tags.all() ``` --- ✂️ `defer()` – exclude heavy fields (e.g., large text) ```python books = Book.objects.defer('description') ``` --- 🎯 `only()` – load only selected fields ```python books = Book.objects.only('title', 'author') ``` --- ✅ These techniques reduce query count, cut down I/O, and boost performance especially under load. --- 🎙️ **Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):** **Optimizing database queries in Django is like asking only for the info you really need, instead of grabbing the whole database every time.** * Let’s say each book has an author, and you want to show the book list with authors’ names. If you don’t optimize, Django might do a separate query for each book’s author — that’s the N+1 problem. * Using `select_related()`, you tell Django: “Hey, grab the book and its author in one go.” * For reverse or many-to-many relationships, use `prefetch_related()`, which makes two queries but joins them smartly in Python. * If you have large fields you don’t need (like a long description), use `defer()` to skip them. Or use `only()` to load just the fields you care about. These techniques make your app faster and your server happier — especially when traffic grows. --- 🔑 **Câu nên nhớ (Highlight để học thuộc):** * “Avoid N+1 with `select_related()` and `prefetch_related()`” * “Use `defer()` to skip heavy fields, `only()` to pick specific ones” * “Optimized queries = fewer DB hits + better performance”
43
❓ **Q: What is the role of a reverse proxy server in Django deployment?**
💡 **Answer:** A reverse proxy server sits in front of Django app servers to improve performance, security, and scalability. It handles tasks like: * **Load Balancing** – Distributes incoming traffic across servers. * **Caching** – Speeds up responses by serving cached data. * **SSL Termination** – Manages HTTPS, offloading encryption from Django. * **Security** – Hides backend details and filters harmful requests. Common tools: **Nginx**, **Apache**, **HAProxy**, **Varnish** ✅ Reverse proxies improve: * **Performance** (less latency) * **Scalability** (handles more users) * **Security** (hides internals, filters traffic) * **Flexibility** (acts as a control layer) --- 🎙️ **Interview-Friendly Casual Explanation (Diễn giải để nói trôi chảy):** **A reverse proxy is like a smart receptionist that handles all incoming traffic before it hits your Django app.** * It can decide which server handles which request — that’s **load balancing**. *For stuff that doesn’t change often, it can just hand out a cached copy without hitting Django again — faster and more efficient. * It also takes care of **SSL (HTTPS)** so Django doesn’t need to handle encryption. * And importantly, it **hides** your backend setup — attackers won’t know if you’re using Django, Flask, or anything else. Most people use **Nginx** or **Apache** for this, and they sit in front of your Gunicorn or uWSGI Django server. --- 🔑 **Câu nên nhớ (Highlight để học thuộc):** * “Reverse proxy = smart middleman between users and Django app” * “Handles SSL, load balancing, caching, and security” * “Nginx is the most common reverse proxy in Django setups”