[Fixed]-RelatedObjectDoesNotExist during form validation

1👍

Setting required=False and disabling the widget is not ideal. Disabling the widget means that your browser will not submit any values for that field. Since you have required=False, this means that the form will set the foreign key to None. However, this is incompatible with the model’s foreign key, which has null=False by default.

I’m not familiar enough with the internals to precisely explain the exception, but the basic problem is that Django is trying to fetch the related unit from the database, after the form has set the foreign key to None.

One work around is to check self.unit_id rather than self.unit. This prevents the database lookup, so you don’t get the exception.

However, this seems a bit dirty to me. If you don’t want the user to edit the unit field, I would remove it from the form completely. Check self.instance.pk to determine whether or not the instance is in the database already.

def __init__(self, *args, **kwargs):
    super(Property1Form, self).__init__(*args, **kwargs)
    if self.instance.pk:
        del self.fields['unit']

Then in your view, you shouldn’t have to set properties.unit = unit any more. I would remove form.unit = unit as well, I don’t think it was ever useful.

Leave a comment