DeleteView
Part of the Class-Based Views section of Coddy's Django journey. Lesson 13 of 18.
Job pages have a Delete link. A delete must never happen on a plain visit: browsers and link previews open pages on their own. So DeleteView works in two steps: GET shows a question, and only the POST from its form deletes. A recipe site:
from django.urls import reverse_lazy
class RecipeDeleteView(DeleteView):
model = Recipe
success_url = reverse_lazy("recipes:home")Its template defaults to recipes/recipe_confirm_delete.html, a file you write. It holds a form with method="post" and {% csrf_token %}, and its button sends the POST that deletes. After the delete there is no row page to land on, so success_url is required.
Use reverse_lazy() there, not reverse(). A class attribute is computed when views.py is imported, before the routes exist, so reverse() stops the project from starting. reverse_lazy() waits until the URL is used.
Challenge
EasyMake the page behind Delete, with the ready template jobs/job_confirm_delete.html.
- In
jobs/views.py, addJobDeleteView, aDeleteViewofJobthat sends the browser tojobs:listafter deleting. - In
jobs/urls.py, add the route"jobs/<slug:slug>/delete/"nameddelete.
Press Delete on a job: the page asks first, and confirming removes it from /jobs/.
Try it yourself
from django.views.generic import CreateView, 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(CreateView):
model = Job
fields = ["title", "company", "city", "salary", "description"]
class JobUpdateView(UpdateView):
model = Job
fields = ["title", "company", "city", "salary", "description"]
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Class-Based Views
Practice on your own: Django playground