UpdateView
本课属于 Coddy Django 学习旅程的“基于类的视图”单元。第 12 课,共 18 课。
发布者需要修改他们发布的职位。编辑一行就是创建一行,只不过表单一开始已经填好,保存时会修改这一行,而不是添加新行。UpdateView 两种操作都能完成。以食谱网站为例:
class RecipeUpdateView(UpdateView):
model = Recipe
fields = ["title", "cuisine", "minutes"]
# urls.py
path("recipes/<int:pk>/change/", views.RecipeUpdateView.as_view(), name="change")它会像 DetailView 一样,根据 URL 中的 pk 或 slug 查找这一行;如果没有匹配的行,就会返回 404。保存后,它会像 CreateView 一样跳转到 success_url,或者跳转到该行的 get_absolute_url()。
它与 CreateView 共用 recipes/recipe_form.html,并将这一行作为 object 添加进去,因此只有在编辑时 {% if object %} 才为 true。必须设置 fields:Django 不会自行猜测访客可以修改哪些字段。
挑战
简单职位页面现在有一个Edit链接。创建它所指向的页面。
- 在
jobs/views.py中,添加JobUpdateView,它是一个针对Job的UpdateView,包含与JobCreateView相同的五个字段。 - 在
jobs/urls.py中,添加名为edit的路由"jobs/<slug:slug>/edit/"。
打开一个职位,点击 Edit 并保存:你会返回该职位页面,并看到所做的更改。
亲手试试
from django.views.generic import CreateView, 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
class JobCreateView(CreateView):
model = Job
fields = ["title", "company", "city", "salary", "description"]
基于类的视图中的所有课
自己练习: Django 在线编辑器