0

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

DrEichenbach
  • 382
  • 1
  • 2
  • 13

2 Answers2

0

Unless you define a model instance on the form creation, you have a generic model definition, not a model instance. Looks like you may want to change the form behavior after user interaction, to do that you have to use a javascript.

Walucas
  • 2,549
  • 1
  • 21
  • 44
0

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.

Daniel Hepper
  • 28,981
  • 10
  • 72
  • 75