3

There is this disabled attribute. But i am not able to apply it to the modelform fields. I am not sure how to. I can add it to forms.Form easily. But since I am using widgets I just dont know where to insert it.

https://docs.djangoproject.com/en/2.0/ref/forms/fields/#disabled

class TestForm(forms.ModelForm):
    class Meta:
        model = Test
        fields = ['date']
        widgets = {'date': forms.TextInput(attrs={'readonly': 'readonly'})}
an0o0nym
  • 1,336
  • 15
  • 33
questnofinterest
  • 281
  • 3
  • 12

3 Answers3

6

I was facing a situation when I wanted to disable some fields when creating . And some fields disabled when editing.

My Env: Python 3, Django 2.1

My Form:

class AddInvoiceForm(forms.ModelForm):
    disabled_fields = ['inv_type', 'report', 'subsidiary']
    class Meta:
        model = models.Invoice
        fields = ('inv_type', 'report', 'subsidiary', 'rate_card', 'reviewed')

    def __init__(self, *args, **kwargs):
        super(AddInvoiceForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            for field in self.disabled_fields:
                self.fields[field].disabled = True
        else:
            self.fields['reviewed'].disabled = True
Arindam Roychowdhury
  • 4,939
  • 5
  • 53
  • 57
3

Try something like this, assuming that your date field is forms.DateField and that you want to use TextInput widget:

class TestForm(forms.ModelForm):
    date = forms.DateField(widget=forms.TextInput, disabled=True)
    class Meta:
        model = Test
        fields = ['date']

This will override the default field definition which is created from your Test model definition.

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.

Read about readonly vs disabled HTML input attributes.

The key note to take out from the above SO post is:

A readonly element is just not editable, but gets sent when the according form submits. a disabled element isn't editable and isn't sent on submit.

From above quote, setting disabled=True is enough, so you dont need to set readonly attribute on your widget.

an0o0nym
  • 1,336
  • 15
  • 33
2
class TestForm(forms.ModelForm):
date = forms.CharField(disabled=True)
class Meta:
    model = Test
    fields = ['date']

    widgets = {
        'date': forms.TextInput(attrs={'readonly': 'readonly'}),
    }
Sumeet Kumar
  • 891
  • 1
  • 10
  • 21