Django Basics — Complete Guide
이 글의 핵심
Learn Django from scratch: project layout, models, migrations, function and class-based views, URLs, templates, and the admin site—with runnable examples.
Introduction
“Batteries-included” web framework
Django is a full-stack framework with authentication, ORM, admin, and much more built in.
1. Getting started with Django
Install and create a project
# Install Django
pip install django
# Create project
django-admin startproject myproject
cd myproject
# Create app
python manage.py startapp blog
# Run dev server
python manage.py runserver
Project layout
myproject/
├── myproject/
│ ├── __init__.py
│ ├── settings.py # configuration
│ ├── urls.py # URL routing
│ └── wsgi.py
├── blog/
│ ├── models.py # models (data)
│ ├── views.py # views (logic)
│ ├── urls.py
│ └── templates/ # templates (UI)
└── manage.py
2. Models
Defining a model
# blog/models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
class Meta:
ordering = ['-created_at']
Migrations
# Create migration files
python manage.py makemigrations
# Apply to database
python manage.py migrate
3. Views
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()
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
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'
paginate_by = 10
class PostDetailView(DetailView):
model = Post
template_name = 'blog/post_detail.html'
4. URL routing
URL patterns
# blog/urls.py
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path(', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
]
# myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
]
5. Templates
Writing templates
<!-- templates/blog/post_list.html -->
<!DOCTYPE html>
<html>
<head>
<title>Blog</title>
</head>
<body>
<h1>Blog posts</h1>
{% for post in posts %}
<article>
<h2>
<a href="{% url 'blog:post_detail' post.pk %}">
{{ post.title }}
</a>
</h2>
<p>{{ post.content|truncatewords:30 }}</p>
<small>{{ post.created_at|date:"Y-m-d H:i" }}</small>
</article>
{% empty %}
<p>No posts yet.</p>
{% endfor %}
</body>
</html>
6. Admin site
Registering models
# blog/admin.py
from django.contrib import admin
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'author', 'created_at']
list_filter = ['created_at', 'author']
search_fields = ['title', 'content']
date_hierarchy = 'created_at'
Create a superuser
python manage.py createsuperuser
# Username: admin
# Email: [email protected]
# Password: ****
# Open http://localhost:8000/admin/
7. Practical example
Simple blog
# blog/views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from .models import Post
def create_post(request):
if request.method == 'POST':
title = request.POST.get('title')
content = request.POST.get('content')
author = request.POST.get('author')
Post.objects.create(
title=title,
content=content,
author=author
)
messages.success(request, 'Post created successfully!')
return redirect('blog:post_list')
return render(request, 'blog/create_post.html')
Summary
Key takeaways
- Django: full-stack web framework
- MVT: Model, View, Template
- ORM: manipulate the DB with Python
- Admin: auto-generated management UI
- Migrations: schema versioning for the database
Next steps
- [REST API design](/en/blog/python-series-13-rest-api/
- [Databases in Python](/en/blog/python-series-14-database/
Related posts
- [Flask basics | Get started with the Python web framework](/en/blog/python-series-11-flask-basics/
자주 묻는 질문 (FAQ)
Q. 이 내용을 실무에서 언제 쓰나요?
A. Learn Django from scratch: project layout, models, migrations, function and class-based views, URLs, templates, and the … 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.
Q. 선행으로 읽으면 좋은 글은?
A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. Python 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.
Q. 더 깊이 공부하려면?
A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- [Flask Basics | Get Started with the Python Web Framework](/en/blog/python-series-11-flask-basics/
- [Python Databases | SQLite, PostgreSQL, and ORMs Explained](/en/blog/python-series-14-database/
- [Python REST APIs | Build API Servers with Flask and Django](/en/blog/python-series-13-rest-api/
이 글에서 다루는 키워드 (관련 검색어)
Python, Django, Web Development, Backend, ORM, MVT, Framework 등으로 검색하시면 이 글이 도움이 됩니다.