I have the following models in my Django app:
class Property(models.Model):
...various attributes...
class Booking(models.Model):
property = models.ForeignKey(
Property
)
...more attributes...
I implemented the clean() method for Booking which checks various constraints of a Booking. A number of these constraints depend on the association of Booking and Property being in place. For that reason I have the following in the clean() method of Booking:
if self.property is not None:
...Property related validations...
Upon entering a new booking in the admin application and just pressing the Save button without entering anything, this generates a DoesNotExist exception on self.property is not None. It’s my understanding that the missing association should be captured by the individual field validation of Django.
When I comment out the clean() method the above doesn’t happen and the missing association is properly flagged as an error when I submit a blank booking form.
I’m obviously missing something but haven’t got a clue what…
Posting as an answer since it was the answer:
I’m not sure of the root cause since I deduced the solution based on the error message. I imagine that the Django ORM might create the foreign key association dynamically upon save, so even though it’s a required attribute it hasn’t been created yet since the Booking instance is new and hasn’t been saved.