jundymek
jundymek

Reputation: 1043

Django - change form field to readonly when value in view is set to any value

In my view.py I have a variable - for example 'email'. In my forms.py I have an email field - for example:

email = forms.EmailField(label="Email adress")

I would like to change this to:

email = forms.EmailField(label="Email adress", widget=forms.TextInput(attrs={'readonly': 'readonly'}))

when email variable from my view.py is filled (from None to any value). By default email is set to None. How can I achieve that?

Upvotes: 0

Views: 624

Answers (1)

Jens Astrup
Jens Astrup

Reputation: 2454

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='[email protected]')
    email = kwargs.get('email', None)
    # Or as initial value form = MyForm(initial={'email': '[email protected]'})
    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

Upvotes: 1

Related Questions