StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 10 · Forms

Event Registration Form

easyDjango FormsInput Validation100%2 of 2 solved

Problem statement

Registration for the event is a raw POST handler: it trusts whatever arrives, so usernames come in with spaces, dates land in the past, the two password boxes never get compared, and people book more guests than the seats they paid for. A rejected attempt loses everything typed and explains nothing. Build the form properly - the fields and their types, the rules that belong to one field, the rules that need two, the page that shows what went wrong, and the view flow that ties them together.

Requirements

Implement:

  • validate_no_spaces(value) in app/forms.py
  • EventRegistrationForm in app/forms.py
  • register in app/views.py
  • the page in app/templates/app/register.html

The following files are already implemented and provided: app/models.py and app/urls.py. EventRegistration holds username and referrer (both CharField(max_length=200)), email (EmailField), event_date (DateField), seats and guests (both IntegerField) and an automatic created_at. The route /register/ is named register and points at register in app/views.py, which already accepts GET and POST. Everything here is a plain forms.Form: nothing on this page needs a model form, a class-based view or Django's auth app.

1. The eight fields, all required

FieldHolds
usernamefree text, no spaces
referrerthe username of the member who referred you, same rule
emailan email address
event_datea date, later than today
seatsa whole number of seats reserved
guestsa whole number of people attending
password1a password, entered masked
password2the same password again, entered masked
  • Those are the field names, and a blank value for any one of them is invalid with the error under that same name in form.errors.
  • username, referrer and email reach cleaned_data with surrounding whitespace stripped; seats and guests reach it as integers; event_date reaches it as a date.
  • A value that is not an email address is an error on email, and a non-numeric guests is an error on guests, because each field class checks its own type.

2. validate_no_spaces - the reusable rule

  • It keeps its name and takes the cleaned value as its one argument, so it can be imported by that name.
  • A value containing a space raises forms.ValidationError with exactly this message:
Username must not contain spaces.
  • The rule guards both username and referrer, each reporting under its own field name. The check itself exists in one place only: that message string appears exactly once in app/forms.py.

3. The date rule on event_date

  • An event_date that is not later than the current local date is invalid, with exactly this message:
The event date must be in the future.
  • Today itself is not in the future and is refused; tomorrow passes. The comparison is against the current local date, so the rule is still right tomorrow rather than against a date written into the file.

4. The two form-wide rules

  • Passwords that differ are invalid, with exactly this message:
The two passwords do not match.
  • More guests than seats is invalid, with exactly this message:
You cannot bring more guests than the seats you reserved.
  • Both land among the form's own errors, reachable through form.non_field_errors(), and on no field. Exactly as many guests as seats is valid.
  • A submission that breaks both reports both, so the first problem found cannot be the only one reported.
  • Neither comparison runs unless both of its values arrived. A blank confirmation is a missing field, not a mismatch, and a blank guests is not over capacity.
  • Field errors never land on the form: a submission with a spaced username and a malformed email leaves form.non_field_errors() empty.

5. The page

  • Build the inputs and both kinds of error area in register.html. Nine elements, each found by its id:
Element idShows
form-errorsevery form-wide error, from form.non_field_errors
error-usernameusername's own errors
error-referrerreferrer's own errors
error-emailemail's own errors
error-event_dateevent_date's own errors
error-seatsseats's own errors
error-guestsguests's own errors
error-password1password1's own errors
error-password2password2's own errors
  • All nine are present on every render, and hold no text when there is nothing to report.
  • Every field renders as an input carrying that field's name, so a rejected submission comes back with the typed values still in their inputs.

6. The view flow in register

  • GET /register/
    • Purpose: display the empty registration page.
    • Response: 200 OK, the form unbound, so no input carries a value.
  • POST /register/
    • Purpose: register one attendee.
    • Response:
      • 302 Found: redirect to the route named register when the submission is valid, with one EventRegistration stored from cleaned_data.
      • 400 Bad Request: the same page re-rendered from the same bound form, so every value typed is still in its input and every error is beside it, with nothing stored at all.
  • A key the form never declared is not part of the submission, so a body carrying an extra field is still valid.

Notes

  • Only app/forms.py, app/views.py and app/templates/app/register.html change.
  • The three places a rule can live, and where its error lands:
WhereSeesError lands on
a validator attached with validators=[...]one valuethat field
clean_<field>one value, plus anything outside the formthat field
clean()every cleaned value togetherthe form
  • A validator is the right home for a rule two fields share. clean_<field> reads self.cleaned_data[...] and must return the value. clean() is the only place that can compare two fields; call super().clean() first, return the dictionary, and reach for values with .get() because a field that failed its own validation is simply absent.
  • Reporting two form-wide problems at once needs care: raise forms.ValidationError(...) leaves clean() immediately, so a second rule below it never runs and its message never appears, while self.add_error(None, ...) records the problem and carries on.
  • Each element is found by its id, and only its text counts, with runs of whitespace collapsed to one space. Extra attributes and classes, wrapper elements and tags inside an element are all fine.
  • Never read request.POST for a value; every stored value comes from cleaned_data.
  • Do not add password strength rules, length limits or any validation beyond the rules above.

More in Forms

See the module
Contact Form BasicsDeclare a Django Form with typed required fields so the contact view stores validated data only.100%2 of 2 solvedeasyCustom Field RulesAdd per-field validation with a clean_<field> method and a reusable validator shared across two forms.100%2 of 2 solvedeasyCross-Field Password CheckCompare two password fields in the form's clean() method and render field and non-field errors in the template.100%2 of 2 solvedeasy

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.