UpdateView
Part of the Class-Based Views section of Coddy's Django journey. Lesson 12 of 18.
Posters need to fix their jobs. Editing a row is creating one, except the form starts filled in and saving changes the row instead of adding one. UpdateView does both. A recipe site:
class RecipeUpdateView(UpdateView):
model = Recipe
fields = ["title", "cuisine", "minutes"]
# urls.py
path("recipes/<int:pk>/change/", views.RecipeUpdateView.as_view(), name="change")It finds the row the way DetailView does, by the pk or slug in the URL, and answers 404 when there is none. After saving it goes where CreateView goes: success_url, or the row's get_absolute_url().
It shares recipes/recipe_form.html with CreateView and adds the row as object, so {% if object %} is true only when editing. fields is required: Django will not guess which fields a visitor may change.
Challenge
EasyJob pages now have an Edit link. Make the page behind it:
- A
JobUpdateView, anUpdateViewofJobwith the same five fields asJobCreateView. - A route
"jobs/<slug:slug>/edit/"namededit.
Press Run, open a job, press Edit and save: you land back on the job with your change.
Try it yourself
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"]
All lessons in Class-Based Views
Practice on your own: Django playground