views.py에서 여러 기능들을 구현할 수 있지만 form 기능의 경우 Django에서 forms.py라는 이름으로 따로 정의 및 구분해 줄 필요가 있습니다.
먼저 blog 앱에 사용될 form부터 정의해주도록 하겠습니다.
blog 폴더 아래 forms.py
라는 파일을 만들어준 뒤 아래의 내용을 작성해줍니다.
# blog/forms.py
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'content']
class CommentForm(forms.ModelForm):
class Meta:
model = Post
fields = ['content']
FBV로 View를 작성해보도록 하겠습니다.
# blog/views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse
from .models import Post
from .forms import PostForm
def post_list(request):
post_list = Post.objects.all()
return render(request, 'blog/post_list.html', {'post_list': post_list})
def post_create(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
post = form.save()
return redirect('blog:detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_form.html', {'form': form})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
def post_update(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == 'POST':
form = PostForm(request.POST, instance=post)
if form.is_valid():
post = form.save()
return redirect('blog:detail', pk=post.pk)
else:
form = PostForm(instance=post)
return render(request, 'blog/post_form.html', {'form': form})
def post_delete(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == 'POST':
post.delete()
return redirect('blog:list')
return render(request, 'blog/post_confirm_delete.html', {'post': post})
CBV로도 View 파트를 작성해보도록 하겠습니다.
# blog/views.py
from django.views import View
from .models import Post
from .forms import PostForm
from django.urls import reverse_lazy
class PostList(View):
def get(self, request):
post_objs = Post.objects.all()
context = {
"posts": post_objs
}
return render(request, 'blog/post_list.html', context)
# blog/views.py
from django.views.generic import ListView, CreateView, DetailView, UpdateView, DeleteView
from .models import Post
from .forms import PostForm
from django.urls import reverse_lazy
class PostListView(ListView):
model = Post
context_object_name = 'post_list'
class PostCreateView(CreateView):
model = Post
form_class = PostForm
success_url = reverse_lazy('blog:list')
class PostDetailView(DetailView):
model = Post
context_object_name = 'post'
class PostUpdateView(UpdateView):
model = Post
context_object_name = 'post_update'
form_class = PostForm
success_url = reverse_lazy('blog:list')
class PostDeleteView(DeleteView):
model = Post