Search code examples
djangodjango-formsdisabled-inputreadonly-attribute

How to make a django form field readonly with the HTML attribute readonly instead of disabled


I want to make my field in a form to be readonly. I have already used disabled in forms but it doesn't send my data to the database when POST request is triggered by the Form.

site_location = forms.CharField(disabled=True)

So, I inspected the element and manually added readonly attribute to its HTML code to check if readonly is working or not. And readonly has no issues in submitting the form. But disabled tells me that my form is invalid.

Readonly and Disabled have some differences according to this answer: What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

How can I use the readonly in forms instead of disabled??


Solution

  • I found it. I don't know why no one uses this. Found it from an old website.

    site_location = forms.CharField(widget=forms.TextInput(attrs={'readonly':'readonly'}))  
    

    This is the best solution.