CreateView
Part of the Class-Based Views section of Coddy's Django journey. Lesson 10 of 18.
The menu has a Post a job link with no page behind it. A page that adds a row is the same code every time: show an empty form, check what was posted, save it, redirect. CreateView is that code, with a ModelForm it builds for you:
from django.views.generic import CreateView
class RecipeCreateView(CreateView):
model = Recipe
fields = ["title", "cuisine", "minutes"]fields lists the form's fields, like a ModelForm's Meta. The template defaults to recipes/recipe_form.html, with the form as form. Invalid data shows the form again with its errors, and nothing is saved.
Put the route "recipes/new/" above "recipes/<slug:slug>/". new is a valid slug, so below it the detail view would take /recipes/new/ and answer 404.
Challenge
MediumThe template jobs/job_form.html is ready. Make the page behind Post a job:
- A
JobCreateView, aCreateViewofJobwith the fieldstitle,company,city,salaryanddescription. - A route
"jobs/new/"namedcreate.
Press Run and post a job. It is saved, then Django stops: No URL to redirect to. The next lesson fixes that.
Try it yourself
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
All lessons in Class-Based Views
Practice on your own: Django playground