[Answered ]-How to set a ModelForm field not editable based on other object?

2👍

The only thing you need to change from the mentioned answer is to edit the if condition:

class ApplicationForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(ApplicationForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.project and instance.project.budget:
            self.fields['budget'].widget.attrs['readonly'] = True

    def clean_budget(self):
        instance = getattr(self, 'instance', None)
        if instance and instance.project and instance.project.budget:
            return instance.budget
        else:
            return self.cleaned_data['budget']

You can pass project to the form constructor via instance argument:

application = Application(project=project)
form = ApplicationForm(instance=application)

Leave a comment