0

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?

1 Answer 1

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='[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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.