Skip to content Skip to sidebar Skip to footer

Why It Happens - Relatedobjectdoesnotexist Error Caused By Model.clean()?

I have a clean method that gives me RelatedObjectDoesNotExist error in my model file @with_author class BOMVersion(models.Model): version = IntegerVersionField( ) name

Solution 1:

When you call is_valid() on the form it's calling the model's clean method. Since you're only assigning material after calling is_valid(), when self.material is called, self.material is not associated with any Materialobject.

Instead of checking that on the clean method, since you already have the Material instance when you're saving the form, you could raise an exception before calling is_valid(). Remove the check from clean and then add:

if model.objects.filter(material=material, is_default=True).count()  > 1:
    raise ValidationError('Material {} has a default value already'.format(material)) 

before calling is_clean() or somewhere before saving the instance.

Post a Comment for "Why It Happens - Relatedobjectdoesnotexist Error Caused By Model.clean()?"