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/, but there is no page there 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
MediumGive each poster a page with their own jobs.
- In
jobs/views.py, addMyJobsView, for signed in users only. It lists their jobs, newest first, on one page. - Create
jobs/my_jobs.htmlfromjobs/base.html: an<h1>Your jobs, then one<li class="job">per job, title in<strong>. With none, showYou have not posted a job yet. - In
jobs/urls.py, addmy-jobs/namedmine.
Log in as ada (coddy-pass-123) and press Your jobs: you see her 6 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