Menu
CoddyTech

CreateView

本课属于 Coddy Django 学习旅程的“基于类的视图”单元。第 10 课,共 18 课。

菜单中有一个 Post a job 链接,但它没有对应的页面。添加一行数据的页面每次都使用相同的代码:显示一个空表单,检查提交的内容,保存数据,然后重定向。CreateView 就是这段代码,它会为你创建一个 ModelForm:

from django.views.generic import CreateView


class RecipeCreateView(CreateView):
    model = Recipe
    fields = ["title", "cuisine", "minutes"]

fields 列出了表单的字段,就像 ModelForm 的 Meta 一样。模板默认为 recipes/recipe_form.html,表单变量名为 form。如果数据无效,页面会再次显示表单和错误信息,并且不会保存任何内容。

将路由 "recipes/new/" 放在 "recipes/<slug:slug>/" 上方。Django 会使用第一个匹配的路由。new 是有效的 slug,因此,如果 slug 路由排在这个路由上方,它就会匹配 /recipes/new/,并返回 404。

challenge icon

挑战

中等

使用现成的模板 jobs/job_form.html,创建 Post a job 页面。

  1. 在 jobs/views.py 中,添加 JobCreateView,它是一个针对 Job 的 CreateView,包含字段 title、company、city、salary 和 description。
  2. 在 jobs/urls.py 中,添加名为 create 的路由 "jobs/new/"。

提交职位后,数据会保存,然后 Django 会显示 No URL to redirect to。下一课会修复这个问题。

亲手试试

from django.views.generic import DetailView, ListView, TemplateView

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

基于类的视图中的所有课

自己练习: Django 在线编辑器