Landing on the New Job
Part of the Class-Based Views section of Coddy's Django journey. Lesson 11 of 18.
Post a job and Django saves it, then stops: No URL to redirect to. After saving, a CreateView redirects to its success_url. Without one, it asks the new row for its address through a model method, get_absolute_url().
The address of a row's page depends on the row, so the method belongs on the model. Build it with reverse(), which turns a route's name and arguments into a URL, as {% url %} does in a template:
class Recipe(models.Model):
...
def get_absolute_url(self):
return reverse("recipes:recipe", kwargs={"pk": self.pk})Give the arguments by name with kwargs={...}, or in order with args=[...], and import reverse from django.urls. A template can link with {{ recipe.get_absolute_url }}, and an UpdateView lands there too.
Challenge
MediumAfter posting, the browser should land on the new job's page:
- In
jobs/models.py, giveJobaget_absolute_url()that returns the URL of its page, the routejobs:detail. - Leave
JobCreateViewas it is.
Press Run and post a job: you land on its page.
Try it yourself
from datetime import date
from django.conf import settings
from django.db import models
from django.utils.text import slugify
class Job(models.Model):
title = models.CharField(max_length=200)
company = models.CharField(max_length=200)
city = models.CharField(max_length=100)
salary = models.PositiveIntegerField(help_text="Yearly, in euros.")
description = models.TextField(blank=True)
posted = models.DateField(default=date.today)
slug = models.SlugField(max_length=220, unique=True, blank=True)
posted_by = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="jobs",
)
def __str__(self):
return f"{self.title} at {self.company}"
def save(self, *args, **kwargs):
# A new job gets a slug from its title and company: "python-developer-acme".
if not self.slug:
base = slugify(f"{self.title} {self.company}") or "job"
slug = base
n = 2
while Job.objects.filter(slug=slug).exists():
slug = f"{base}-{n}"
n += 1
self.slug = slug
super().save(*args, **kwargs)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Class-Based Views
4Editing Views
CreateViewLanding on the New JobPractice on your own: Django playground