Menu
CoddyTech

Setting the Poster

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

Every Job has a posted_by field, and new jobs leave it empty. It must not be a form field, or anyone could post in someone else's name. The view fills it in.

For a valid form, an editing view calls form_valid(form), which saves the row and redirects. Override it to change the row first. A recipe site saves each review on the recipe in its URL, recipes/<slug:slug>/review/:

class ReviewCreateView(LoginRequiredMixin, CreateView):
    model = Review
    fields = ["stars", "text"]

    def form_valid(self, form):
        recipe = get_object_or_404(Recipe, slug=self.kwargs["slug"])
        form.instance.recipe = recipe
        return super().form_valid(form)

form.instance is the unsaved row, and self.kwargs holds the URL arguments. Set your field, then let super().form_valid(form) save and redirect. Set it after super() and the row is already saved without it.

challenge icon

Challenge

Easy

In JobCreateView, override form_valid() so a new job's posted_by is the logged-in user. Keep posted_by out of fields.

Press Run, log in as grace (coddy-pass-123) and post a job: its page says by grace after the date.

Try it yourself

from django.contrib.auth.mixins import LoginRequiredMixin
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"]


class JobUpdateView(LoginRequiredMixin, UpdateView):
    model = Job
    fields = ["title", "company", "city", "salary", "description"]


class JobDeleteView(LoginRequiredMixin, DeleteView):
    model = Job
    success_url = reverse_lazy("jobs:list")

All lessons in Class-Based Views

Practice on your own: Django playground