게시자 설정하기
Coddy Django 여정의 클래스 기반 뷰 섹션에 포함된 레슨. 18개 중 15번째.
모든 Job에는 posted_by 필드가 있으며, 새 작업에서는 이 필드가 비어 있습니다. 이 필드는 양식 필드가 되어서는 안 됩니다. 누구나 다른 사람의 이름으로 게시할 수 있기 때문입니다. 뷰에서 이 필드를 채웁니다.
유효한 양식의 경우, 편집 뷰는 form_valid(form)을 호출하여 행을 저장하고 리디렉션합니다. 먼저 행을 변경하려면 이 메서드를 재정의하세요. 레시피 사이트에서는 URL에 포함된 레시피에 각 리뷰를 저장합니다. URL은 recipes/<slug:slug>/review/입니다.
class ReviewCreateView(LoginRequiredMixin, CreateView):
model = Review
fields = ["stars", "text"]
def form_valid(self, form):
recipe = get_object_or_404(Recipe, slug=self.kwargs["slug"])
form.instance.recipe = recipe
return super().form_valid(form)form.instance는 아직 저장되지 않은 행이며, self.kwargs에는 URL 인수가 들어 있습니다. 필드를 설정한 다음 super().form_valid(form)이 저장하고 리디렉션하도록 하세요. super()를 호출한 뒤에 필드를 설정하면 해당 필드 없이 행이 이미 저장된 상태입니다.
챌린지
쉬움JobCreateView에서 form_valid()를 재정의하여 새 구직 공고의 posted_by가 로그인한 사용자가 되도록 하세요. posted_by는 fields에 넣지 마세요.
실행을 누르고 grace(coddy-pass-123)로 로그인한 다음 구직 공고를 게시하세요. 공고 페이지에는 날짜 뒤에 by grace가 표시됩니다.
직접 해보기
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.views.generic import CreateView, DeleteView, DetailView, ListView, TemplateView, UpdateView
from .models import Job
class HomeView(TemplateView):
template_name = "jobs/home.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["count"] = Job.objects.count()
context["latest"] = Job.objects.order_by("-posted").first()
return context
class AboutView(TemplateView):
template_name = "jobs/about.html"
class JobListView(ListView):
model = Job
context_object_name = "jobs"
ordering = ["-posted"]
paginate_by = 5
def get_queryset(self):
jobs = super().get_queryset()
city = self.request.GET.get("city")
if city:
jobs = jobs.filter(city=city)
return jobs
class JobDetailView(DetailView):
model = Job
class JobCreateView(LoginRequiredMixin, CreateView):
model = Job
fields = ["title", "company", "city", "salary", "description"]
class JobUpdateView(LoginRequiredMixin, UpdateView):
model = Job
fields = ["title", "company", "city", "salary", "description"]
class JobDeleteView(LoginRequiredMixin, DeleteView):
model = Job
success_url = reverse_lazy("jobs:list")
클래스 기반 뷰의 모든 레슨
직접 연습해 보세요: Django 플레이그라운드