Lesson 14 — Model validation
Refuse bad data with an exception
A model can protect itself: if a value is wrong, it raises an exception (an error that stops the normal flow). Django models do this in clean() with ValidationError; here we use Python's ValueError.
if age < 0:
raise ValueError("age must be >= 0")
The caller catches it with try / except and shows a friendly message instead of crashing.
Note: the exercise runs in your browser without Django installed, so it is a small plain-Python simulation of what Django does for you.
Why it matters: rules that live in the model are enforced everywhere the model is used.
Make Product raise ValueError("price must be >= 0") for a negative price, so the second line is caught.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
A quick 3-question quiz on this lesson — instant feedback.