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

Product ModelForm

mediumDjango Model FormsModels100%2 of 2 solved

Problem statement

In this Django project, implement the new-product page on top of the Product model instead of a hand-written field list. Build ProductForm in app/forms.py as a ModelForm carrying the widgets and labels the page needs, and finish product_create in app/views.py so the server stamps the listing code on its way to the database. This keeps the form and the model from drifting apart and keeps a server-owned column out of the browser's reach.

Requirements

Implement:

  • ProductForm in app/forms.py
  • product_create in app/views.py

The following files are already implemented and provided: app/models.py, app/urls.py, and both templates. Product holds name (CharField(max_length=120)), sku (CharField(max_length=20), matched against ^[A-Z]{3}-\d{4}$), price (DecimalField(max_digits=8, decimal_places=2), at least 0.01), description (TextField(blank=True)), available_from (DateField) and listing_code (CharField(max_length=40, blank=True, default=""), which the server stamps and the browser never sends). app/models.py also exports LISTING_PREFIX, whose value is WEB. app/templates/app/product_form.html prints the form with as_p and app/templates/app/product_list.html lists each product with its listing code.

1. ProductForm - derived from the model

  • Meta names the model, and the form's fields are exactly name, sku, price, description and available_from, in that order.
  • listing_code is not among them, and fields = "__all__" does not meet this requirement: a column the server owns is kept safe by being left out of the field list, not by being checked after the fact.
  • Do not restate a field's type, length or validators on the form. The model's own validators then report through form.errors under the field's name, with the model's messages:
SKU must look like ABC-1234.
Price must be at least 0.01.
  • Widgets, three overrides, everything else left as the model's guess:
  • price: forms.NumberInput with step="0.01" and placeholder="0.00"
  • description: forms.Textarea with rows="3" and cols="50"
  • available_from: forms.DateInput with type="date"
  • Labels, all five fields: name is Product name, sku is Stock code, price is Unit price (USD), description is Shelf description, available_from is On sale from.

2. GET /products/new/

  • Purpose: Display the empty product form.
  • Response:
  • 200 OK: the form rendered unbound, so every declared field appears and none of them carries a value.

3. POST /products/new/

  • Purpose: Create a product and stamp its listing code.
  • Validation: the model's own sku and price rules, inherited by the form.
  • Response:
  • 302 Found: redirect to the route named product-list when the submission is valid, with one row stored.
  • 200 OK: the same page re-rendered with the submitted values in the inputs and each error on its own field, with nothing written at all.
  • A valid submission is taken as an instance without the write, so the view can set listing_code to LISTING_PREFIX and the product's own SKU joined by a hyphen - WEB-LMP-0042 for SKU LMP-0042 - before the row is saved, never after.
  • A listing_code the browser sends anyway is ignored rather than refused, because a field the form never declared is not part of the submission at all.

Notes

  • Build the listing code from LISTING_PREFIX and the redirect from the route name, rather than writing either literal into the view.
  • app/templates/app/product_list.html is given and works; the catalogue page already lists what is stored.
  • The widgets and labels are the only places the form overrides what the model already describes.

More in ModelForms & Formsets

See the module
Unique Slug ValidationA duplicate slug reaches the database instead of coming back as a form error, and editing a page false-positives against its own slug. Layer the slug rules and a self-excluding uniqueness check on the ModelForm, with a unique constraint on the model as the backstop.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.