Django Core Concepts
Understanding Django's fundamental principles
🎯 What are Django Core Concepts?
Django follows the MVT (Model-View-Template) pattern. Models define data structure, Views handle logic, and Templates display content. Understanding these concepts is essential for building Django applications effectively.
# MVT Pattern Example
# Model → View → Template → User
MVT Architecture
Model
Data structure and database
class Article(models.Model):
title = models.CharField()
View
Business logic and processing
def article_list(request):
articles = Article.objects.all()
Template
HTML presentation layer
<h1>{{ article.title }}</h1>
URL Dispatcher
Routes requests to views
path('articles/', article_list)
🔹 Models - Data Layer
Models represent your database tables as Python classes. Each model maps to a single database table and defines the structure and behavior of your data.
# blog/models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.ForeignKey(Author, on_delete=models.CASCADE)
published_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Common Field Types:
- CharField: Short text (max_length required)
- TextField: Long text content
- IntegerField: Whole numbers
- DateTimeField: Date and time
- ForeignKey: Relationship to another model
🔹 Views - Logic Layer
Views receive web requests and return web responses. They contain the business logic that processes data from models and passes it to templates.
🔸 Function-Based Views
# blog/views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.objects.all().order_by('-published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
🔸 Class-Based Views
# blog/views.py
from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
model = Post
template_name = 'blog/post_list.html'
context_object_name = 'posts'
ordering = ['-published_date']
class PostDetailView(DetailView):
model = Post
template_name = 'blog/post_detail.html'
🔹 Templates - Presentation Layer
Templates are HTML files with Django template language syntax. They display data passed from views and support logic like loops and conditionals.
<!-- templates/blog/post_list.html -->
{% extends 'base.html' %}
{% block title %}Blog Posts{% endblock %}
{% block content %}
<h1>All Blog Posts</h1>
{% if posts %}
{% for post in posts %}
<article>
<h2>{{ post.title }}</h2>
<p>By {{ post.author.name }} on {{ post.published_date|date:"F d, Y" }}</p>
<p>{{ post.content|truncatewords:30 }}</p>
<a href="{% url 'post_detail' post.pk %}">Read More</a>
</article>
{% endfor %}
{% else %}
<p>No posts available.</p>
{% endif %}
{% endblock %}
Template Tags & Filters:
- {{ variable }}: Display variable value
- {% tag %}: Template logic (if, for, etc.)
- {{ value|filter }}: Modify display (date, truncate)
- {% url %}: Generate URLs dynamically
🔹 URL Routing
Django's URL dispatcher maps URL patterns to views. It determines which view function handles each incoming request based on the URL path.
# blog/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
]
# mysite/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
]
URL Examples:
http://example.com/blog/ → post_list view
http://example.com/blog/post/5/ → post_detail view (pk=5)
🔹 Django ORM (Object-Relational Mapping)
Django's ORM lets you interact with databases using Python code instead of SQL. It translates Python operations into database queries automatically.
# Query examples
from blog.models import Post, Author
# Create
post = Post.objects.create(
title="My First Post",
content="Hello World!",
author=author
)
# Read
all_posts = Post.objects.all()
recent_posts = Post.objects.filter(published_date__year=2024)
single_post = Post.objects.get(pk=1)
# Update
post.title = "Updated Title"
post.save()
# Delete
post.delete()
🔹 Django Admin Interface
Django provides a built-in admin interface for managing your data. Register your models to make them editable through the admin panel.
# blog/admin.py
from django.contrib import admin
from .models import Post, Author
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'author', 'published_date']
list_filter = ['published_date', 'author']
search_fields = ['title', 'content']
admin.site.register(Author)
# Create admin user
python manage.py createsuperuser
Access admin at: http://127.0.0.1:8000/admin/
🔹 Request-Response Cycle
Understanding how Django processes requests helps you build better applications:
- User Request: Browser sends HTTP request
- URL Dispatcher: Matches URL to view
- View Processing: View retrieves data from models
- Template Rendering: Data inserted into HTML template
- HTTP Response: Rendered HTML sent to browser
# Complete example
# 1. URL matches pattern
path('posts/', views.post_list)
# 2. View processes request
def post_list(request):
posts = Post.objects.all() # Get data from model
return render(request, 'blog/post_list.html', {'posts': posts})
# 3. Template renders
# {{ post.title }} displays each post