I have the following model:
class Damage(models.Model):
kind = models.ForeignKey(Kind, on_delete=models.PROTECT)
region = models.ForeignKey(Region, on_delete=models.PROTECT)
def clean(self):
if self.region not in self.kind.regions.all():
raise ValidationError('not possible')
and the corresponding form:
class DamageForm(forms.ModelForm):
class Meta:
model = Damage
fields = ['kind', 'region']
when I run the following tests, I always get the django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: Damage has no region
failure.
def test_empty_input(self):
data = {
'kind': None,
'region': None,
}
form = DamageForm(data)
self.assertFalse(form.is_valid())
def test_invalid_input(self):
data = {
'kind': self.test_kind,
'region': self.test_region,
}
form = DamageForm(data)
self.assertFalse(form.is_valid())
Check that the region_id
and self.kind_id
are not None
before trying to access self.region
or self.kind
in your clean
method.
def clean(self):
if self.region_id is not None self.kind_id is not None and self.region not in self.kind.regions.all():
raise ValidationError('not possible')