Search code examples
djangodjango-modelsdjango-formsdjango-templatesdjango-widget

Django widget that depends on model


I am pretty new to django and have a question. I got a ModelForm using Widgets. Since I have a field called discount which I only want to be editable if the displayed model fullfills some requirements, I make it read-only using a widget entry:

class Meta: widgets = {'discount': forms.TextInput(attrs={'readonly': True})}

Now I want to make it possible to write to this field again, iff the Model (here called Order) has its field type set to integer value 0.

I tried to do so in the html template but failed. So my next idea is to make the widget somehow dependent to the model it displays, so in kinda pseudocode:

class Meta: widgets = {'discount': forms.TextInput(attrs={'readonly': currentModel.type == 0})}

Is there a proper way to do something like this? Thanks in advance


Solution

  • You can overwrite __init__ of your model form class to modify the widget:

    class MyModelForm(...):
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs):
            instance = kwargs['instance']
            self.fields['discount'].widget.attrs['readonly'] = instance.type == 0
    

    Might be worth noting that setting the widget to readonly does not prevent a malicious user to modify the field anyways. Make sure to properly validate on the server side.