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: admin@example.com
# 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
Related posts
Frequently Asked Questions (FAQ)
Q. When would I use this in practice?
A. Learn Django from scratch: project layout, models, migrations, function and class-based views, URLs, templates, and the …
Q. What should I read before this?
A. Follow the previous article or related articles links at the bottom of each post to learn in sequence. See the Python series index for the full picture.
Q. Where can I study this more deeply?
A. Check cppreference and the relevant library’s official documentation. The reference links at the end of the article are also worth using.
Related Articles (Internal Links)
Other articles related to this topic.
- Flask Basics | Get Started with the Python Web Framework
- Python Databases | SQLite, PostgreSQL, and ORMs Explained
- Python REST APIs | Build API Servers with Flask and Django
Keywords Covered in This Article (Related Search Terms)
This article covers Python, Django, Web Development, Backend, ORM, MVT, Framework.