I am struggling trying to disable it, but I am using the same form
for two different views, and on one view I need to disable or readonly a field, how can I reach this?
I reach this so far on VIEWS.py
obj = ModelUpdate.objects.first()
field_object = ModelUpdate._meta.get_field('myfield')
field_value = getattr(obj, field_object.attname)
CodePudding user response:
I presume you want to re-use a form in two separate views but have one version have a readonly field? If so, you could either have two versions of the form in your forms.py
file, if the form code is not particularly long, or you could add some sort of check in the def __init__
of the form to set the field as readonly under a certain condition:
my_field = forms.CharField(widget=forms.TextInput(attrs={'readonly':'readonly'}))
Edit:
If you don't want two separate forms, you could do this:
class MyForm(forms.ModelForm):
...
def __init__(self, my_field_is_read_only=False, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
if my_field_is_read_only:
self.fields['my_field'].widget.attrs['readonly'] = True
CodePudding user response:
You can use inheritance.
class AbstractForm(forms.Form):
# General fields
class AllEditableForm(AbstractForm):
# The field which we will allow to edit
target_field = forms.XXXXField()
class OneFieldReadOnly(AbstractForm):
# Make the field read only
target_field = forms.XXXXField(disabled=True)