Job Search
Part of the Class-Based Views section of Coddy's Django journey. Lesson 18 of 18.
The last feature is a search box on the jobs page. A visitor types developer, presses Search, and sees only the jobs with that word in the title.
A search form uses GET, so the word lands in the URL as ?q=developer, where a link or a bookmark keeps it. The view reads it the way it reads ?city=, in get_queryset(). People type in any case, so match with a lookup that ignores it.
Filters chain: narrow by city when there is one, then by the word when there is one. The pagination links already use {% querystring %}, so a search survives the page change.
Challenge
MediumAdd a search to /jobs/:
- A GET form at the top with a box named
qand aSearchbutton. The box keeps the searched word. ?q=developerlists the jobs whose title containsdeveloper, in any case.?q=engineer&city=Berlinlists the Berlin engineer jobs.
Press Run and search for developer.
Try it yourself
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.urls import reverse_lazy
from django.views.generic import CreateView, DeleteView, 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(LoginRequiredMixin, CreateView):
model = Job
fields = ["title", "company", "city", "salary", "description"]
def form_valid(self, form):
form.instance.posted_by = self.request.user
return super().form_valid(form)
class JobUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Job
fields = ["title", "company", "city", "salary", "description"]
def test_func(self):
return self.get_object().posted_by == self.request.user
class JobDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Job
success_url = reverse_lazy("jobs:list")
def test_func(self):
return self.get_object().posted_by == self.request.user
class MyJobsView(LoginRequiredMixin, ListView):
template_name = "jobs/my_jobs.html"
context_object_name = "jobs"
def get_queryset(self):
return Job.objects.filter(posted_by=self.request.user).order_by("-posted")
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