Menu
CoddyTech

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 form with method="post" and {% csrf_token %}. 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 icon

Challenge

Easy

The template jobs/job_confirm_delete.html is ready. Make the page behind Delete:

  • A JobDeleteView, a DeleteView of Job that sends the browser to jobs:list after deleting.
  • A route "jobs/<slug:slug>/delete/" named delete.

Press Run, open a job and press Delete, then confirm.

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"]
quiz iconTest yourself

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