设置发布者
本课属于 Coddy Django 学习旅程的“基于类的视图”单元。第 15 课,共 18 课。
每个 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 在线编辑器