简体   繁体   中英

Read-Only Field in Django Form

How do I set a field to read-only in a Django form? I know how to disable a field but that's not what I'm looking for. Any help would be appreciated.

You can use the optional attrs parameter when defining the Field . To wit:

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

In django 1.9 in a Field.disabled attribute available : https://docs.djangoproject.com/en/1.9/ref/forms/fields/#disabled

The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won't be editable by users. Even if a user tampers with the field's value submitted to the server, it will be ignored in favor of the value from the form's initial data.

otherwise

use the widget 'readonly' attribute

class PatientForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
       super(PatientForm, self).__init__(*args, **kwargs)
       self.fields['field'].widget.attrs['readonly'] = True

    class Meta:
        model = Patient

Django 1.9+

somefield = forms.CharField(disabled=True)

Here is the only way I get it to work in Js:

function myFieldOnChange() {
    var myField= document.getElementById("myFieldID")
    myField.setAttribute('readonly', true)

Maybe one of the best way to do it in front side is widget-tweak even more if you use your form in multiple view.

If you don't want to install extra lib you can simply add field manually and use the django input attribut. Like this:

<input 
    name="{{ form.fieldname.name }}" 
    type="{{ form.fieldname.widget.input_type }}" 
    readonly="readonly"
    >
</input>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM