1

I have Application (in the sense of applying for something) for Project which is covered by ApplicationForm which extends ModelForm. Application has a required budget, which makes it a required field in ApplicationForm.

If the project has a preset budget, applications against it cannot have their budgets editable on create nor on update. I found this answer on how to set a field as read-only and how to scrub that field, https://stackoverflow.com/a/325038/604511

So how do I create ApplicationForm objects that behave this way based on parent Project?

Community
  • 1
  • 1
Jesvin Jose
  • 22,498
  • 32
  • 109
  • 202

1 Answers1

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)
catavaran
  • 44,703
  • 8
  • 98
  • 85
  • but a **new** ApplicationForm must change its behavior for project. I must pass the project earlier. Trying to do it by _init__'s kwargs gives me errors about unexcpected kwargs. – Jesvin Jose Jan 19 '15 at 13:26
  • It would have been a disappointing work day without your answer! – Jesvin Jose Jan 19 '15 at 14:36