[Fixed]-Django – change form field to readonly when value in view is set to any value

1👍

You can use the Form init() to set the attributes:

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    # Either pass as kwarg form = MyForm(email='some@email.com')
    email = kwargs.get('email', None)
    # Or as initial value form = MyForm(initial={'email': 'some@email.com'})
    email = self.fields['email'].initial

    if email is not None:
        self.fields['email'].attrs.update({'readonly': 'readonly'})
        # or you could potentially do this, depending on what you're trying to achieve
        self.fields['email'].disabled = True

Leave a comment