0

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).

Viktor
  • 325
  • 2
  • 10
  • 1
    You can use `self.fields[field_name].initial` or `self["field_name"].value()` or `self.instance`. – NKSM Aug 03 '22 at 12:42
  • ```self["field_name"].value()``` works, thanks. ```self.fields[field_name].initial``` returns ```None``` for all fields at this case. – Viktor Aug 03 '22 at 12:49
  • You can use instead an attribute `readonly`. A form will still submit an input field that is `readonly`, but will not submit an input field that is `disabled`!. You can also add it in `__init__` method, [look at this](https://stackoverflow.com/a/66108267/6143954) – NKSM Aug 03 '22 at 16:57

0 Answers0