[Answer]-Django, adding a readonly field (from instance method) to a modelform.

1👍

Oke, my solution will be quite hacky, but you could maybe do something like this:

class YourModelForm(forms.ModelForm):
    class Meta:
        model = YourModel
        fields = []

    def __init__(self, *args, *kwargs):
        super(YourModelForm, self).__init__(*args, **kwargs)
        # You can also user insert, to add on a certain position
        self.visible_fields.append(self.instance.method())

Now a problem could be that you append a value, because I don’t know how you render your fields. But you could fix this by append a Field-like object, which returns escaped (and saved) html on the necessary methods you call.

Other hacky option, add an additional field, set with an widget its attributes to disabled=disabled, and since a disabled input value isn’t submitted with the form, set it required=False.

Leave a comment