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>/". Django uses the first route that matches. new is a valid slug, so a slug route above this one catches /recipes/new/ and responds with 404.
Challenge
MediumMake the page behind Post a job, with the ready template jobs/job_form.html.
- In
jobs/views.py, addJobCreateView, aCreateViewofJobwith the fieldstitle,company,city,salaryanddescription. - In
jobs/urls.py, add the route"jobs/new/"namedcreate.
Post a job: it is saved, then Django stops with No URL to redirect to, which the next lesson fixes.
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