[Answer]-Django inline set readonly field by condition

1👍

From what I understand you are trying to set a django modelform not a model field to readonly/disabled, depending on some statement like if(condition is true){ dothis(); }

Step 1.

You first will have to create a new FormField class by subclassing django.forms.Field.

You then will have to create a clean() function in your overriden form field class and add a conditional statement to it. See below for an example

from django import forms.Field 
class MyCustomFormField(forms.Field):
      clean(self):
          if self.instance.is_disabled
               return self.instance.field
          else:
               return self.cleaned_data.get('field')

Step 2.

Then in your loop of all fields in you form, when you have your if statement just add this
modelform.fields['field_1'].widget.attrs['readonly'] = True to make the field disabled

`

Leave a comment