Menu
CoddyTech

Your Jobs Page

Part of the Class-Based Views section of Coddy's Django journey. Lesson 17 of 18.

Posters want one place for the jobs they posted. The menu already shows logged-in users a Your jobs link to /my-jobs/, and nothing answers it yet.

From here you build with what this section taught, without an example. The page is a list, so it is a ListView. Its rows depend on who asks, so they are chosen in get_queryset(), where self.request.user is at hand. Only a logged-in user has jobs to see. Give it a template of its own: jobs/job_list.html belongs to the public list.

challenge icon

Challenge

Medium

Add /my-jobs/, a route named mine:

  • Logged-out visitors are sent to log in.
  • A user sees the heading Your jobs and all their jobs on one page, newest first, each in <li class="job"> with the title in <strong>.
  • With none: You have not posted a job yet.

Press Run, log in as ada and press Your jobs.

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

All lessons in Class-Based Views

Practice on your own: Django playground