Skip to content

Core Components#

Model Definition#

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)
    body = models.TextField()
    is_published = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

Function-Based View (FBV)#

from django.shortcuts import render, get_object_or_404
from .models import Post

def post_detail(request, slug):
    post = get_object_or_404(Post, slug=slug)
    return render(request, 'blog/detail.html', {'post': post})

Class-Based View (CBV)#

from django.views.generic import ListView
from .models import Post

class PostListView(ListView):
    model = Post
    template_name = 'blog/list.html'
    context_object_name = 'posts'

App URL Routing#

# myapp/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.PostListView.as_view(), name='list'),
    path('<slug:slug>/', views.post_detail, name='detail'),
]

Project URL Routing#

# myproject/urls.py
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('myapp.urls')),
]

Template Inheritance (Base)#

<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<body>
    <header>Header Content</header>
    {% block content %}{% endblock %}
</body>
</html>

Template Usage (Child)#

<!-- templates/blog/list.html -->
{% extends "base.html" %}

{% block content %}
    {% for post in posts %}
        <h2>{{ post.title }}</h2>
    {% endfor %}
{% endblock %}