StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 8 · ModelForms & Formsets

Unique Slug Validation

mediumDjango Model FormsInput Validation100%2 of 2 solved

Problem statement

In this Django project, implement the slug rules a page is addressed by. Build clean_slug on PageForm in app/forms.py to reject a malformed slug and a slug another page already owns, and make the slug column unique in app/models.py. This turns a database crash into a readable message while keeping the rule enforced for every writer, and it still lets a page resubmit its own slug unchanged.

Requirements

Implement:

  • clean_slug on PageForm in app/forms.py
  • the uniqueness constraint on Page.slug in app/models.py

The following files are already implemented and provided: app/views.py, app/urls.py and both templates. Page holds title (CharField(max_length=120)), slug (SlugField(max_length=80)) and body (TextField). PageForm is already a ModelForm over all three and already saves; keep Meta.fields as it is. Both views re-render their page when the form reports itself invalid and redirect to /pages/ when it saves, so whether a bad slug becomes a message or a crash is decided entirely by the form.

1. The slug's shape

  • A slug shorter than 5 characters is invalid.
  • A slug containing anything other than lowercase letters, digits and single hyphens is invalid, so upper case, underscores and -- are all out.
  • A slug that begins or ends with a hyphen is invalid, even when its characters are otherwise allowed.
  • Each rule raises its own message, so -spring-sale is reported as a hyphen at the edge and not as a character problem. The three messages are compared character for character:
Slug must be at least 5 characters long.
Slug must use lowercase letters, digits and single hyphens only.
Slug must not begin or end with a hyphen.
  • Every one of these errors lands under the slug key of form.errors, never on the form as a whole.
  • Put the shape rules on the form rather than on the model field, so each one can carry its own message. A validator declared on Page.slug does not meet this requirement.

2. The slug nobody else has

  • A slug another page already stores is invalid, with this message:
That slug is already taken.
  • The page being edited is the one row the uniqueness query must not count. On a create there is no such row to exclude, because the unsaved instance has no primary key yet.

3. POST /pages/new/

  • Purpose: Create a page.
  • Response:
  • 302 Found: redirect to /pages/ when the slug is free, with the page stored.
  • 200 OK: the form re-rendered with the error on the slug field when the slug is taken or malformed, with nothing stored and no exception from the database.

4. POST /pages/<slug>/edit/

  • Purpose: Update a page.
  • Response:
  • 302 Found: redirect to /pages/ when the page resubmits its own slug unchanged, or takes a free one.
  • 200 OK: the form re-rendered with That slug is already taken. when the slug belongs to a different page, with nothing written.

5. The constraint underneath

  • slug is unique in Page's own definition, so a write that never goes through the form - a management command, a data import, a plain Page.objects.create(...) - is refused by the database with an IntegrityError rather than silently stored.

Notes

  • Django's own SlugField validation is broad: it accepts upper case, underscores, runs of hyphens and a hyphen at either end. The rules above are narrower, so they are yours to write.
  • Do not reach for request data, signals or anything outside the form and the model.
  • The run command calls makemigrations app before migrate, so the schema is whatever the model says.

More in ModelForms & Formsets

See the module
Product ModelFormA product form restates every model field by hand, so it drifts from the model and the model's own rules never reach it. Derive the form from the model with Meta, give the declared fields their widgets and labels, and save through the form with commit=False so the view can stamp the server-set listing code.100%2 of 2 solvedmediumBulk Ticket FormsetRegistering a group one attendee at a time leaves half the group saved when a row fails. Handle the whole group as one formset submission: a fixed number of rows, a delete box per saved row, validation across every row before anything is written, and an all-or-nothing save.100%2 of 2 solvedmediumInvoice With Line ItemsAn invoice is a header plus a growable table of lines, and a single form cannot take both or keep them consistent. Build the editor from a header ModelForm and an inline item formset bound to the parent, layer field, form and cross-formset rules over it, and save parent and children together inside one transaction.100%2 of 2 solvedmedium

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.