클래스형 뷰(Class-Based Views)
- 개발자들이 자주 쓸만한 view를 클래스로 만들어 둔 것
- 장고는 CRUD 각각을 위한 클래스형 뷰를 제공
예시
from django.views import View
class PostCreateView(View):
def get(self, request):
post_form = PostForm()
return render(request, 'posts/post_form.html', {'form': post_form})
def post(self, request):
post_form = PostForm(request.POST)
if post_form.is_valid():
new_post = post_form.save()
retrn redirect('post-detail', post_id=new_post.id)
제네릭 뷰(Generic View)
- 개발자들이 자주 쓸만한 view를 하나의 형태로 만들어 둔 것
- 자주 사용하는 기능이 미리 구현되어 있어 제네릭 뷰를 상속하면 빠르게 제작 가능
예시
from django.views.generic import CreateView
from django.urls import reverse
class PostCreateView(CreateView):
model = Post
form_class = PostForm
template_name = 'posts/post_form.html'
def get_success_url(self):
return reverse('post-detail', kwargs={'post_id': self.object.id})
- reverse()
- 인자로 받은 url name으로 부터 거슬러 올라가서 url을 찾는 함수
from django.views.generic import ListView
from django.urls import reverse
class PostListView(ListView):
model = Post
form_class = PostForm
template_name = 'posts/post_list.html'
context_object_name = 'posts'
ordering = ['dt_created']
paginate_by = 6
page_kwarg = 'page'
Generic View 정리
- 제네릭 뷰는 역할에 따라 크게 네 가지로 나누어짐
Context 정리
- View에서 Template으로 전달되어 렌더링시 사용할 수 있는 사전형 데이터 변수
- render 함수의 세 번째 파라미터
- Django의 Generic 뷰는 이러한 Context를 각각의 기능에 맞게 자동으로 Template에 전달
def function_view(request):
return render(request, template_name, context)
모델(Model) 데이터
- 모델(Model) 데이터는 Template에 context로 전달
- 하나의 데이터를 다루는 View는 하나의 데이터를 'object'라는 키워드로 전달
- 여러개의 데이터를 다루는 View는 'object_list'라는 키워드로 전달
- 같은 데이터를 'model' 클래스 변수에 명시한 Model을 보고 소문자로 변형해 함께 전달
from django.views.generic import DetailView
from .models import Post
class PostDetailView(DetailView):
model = Post
...
- DetailView는 하나의 데이터를 다루는 로직을 수행
- model 클래스 변수를 지정하면 자동으로 ‘object’라는 키워드로 데이터베이스에서 조회한 하나의 Post 데이터를 Template에 전달
- Template에서는 템플릿 변수를 사용해서 {{object.title}} 같은 형태로 접근
- 이 object와 똑같은 데이터를 모델명을 소문자로 쓴 형태인 post로도 Template에 함께 전달
- 즉, 같은 데이터가 object와 post 두 개의 키워드로 전달
from django.views.generic import ListView
from .models import Post
class PostListView(ListView):
model = Post
...
- ListView는 여러 데이터를 다루는 로직을 수행
- model 클래스 변수를 지정하면 자동으로 데이터베이스에서 조회한 Post 데이터 목록을
object_list라는 키워드로 Template에 전달
- 똑같은 데이터를 model 키워드 변수에 명시된 모델을 참고하여 소문자로 쓴 형태인
<model_name>_list 즉 post_list 키워드로도 context를 전달
- Template에서는 object_list와 post_list 두 개의 키워드로 Post 데이터 목록에 접근할 수 있음
context_obejct_name
- 모델명을 보고 유추하는 <model_name> 또는 <model_name>_list 같은 이름들을 바꿔주는 것
from django.views.generic import ListView
from .models import Post
class PostListView(ListView):
model = Post
context_object_name = 'posts'
...
post_list 가 posts로 변경되어 전달
- Post 데이터목록이
object_list와 posts 두 개의 키워드로 전달