I would like to make the certain field in my formset read-only once the value has been chosen. Kind of like this:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.fields["my_field"].value is not None:
self.fields["my_field"].disabled == True
Except ModelChoiceField object doesn't have an argument value
and I am not even sure __init__
it is the right place to try access value of a formset form's field.
UPDATE
if self["my_field"].value() is not None:
self.fields["my_field"].disabled = True
does the trick. But reveals another issue. When I change the other field's value in this form and try and save it, I get This field is required.
error on the disabled field. Does disabled
argument have any effect on the fields value in form.is_valid
? Because according to man 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.
And initial data is actually None
. I guess I need to find another way to make the field read-only (like simply ignore the change in the post
).