I have a ModelForm with ModelChoiceField on it, and I need to make sure, that the initial value should stay fixed and we can't select any other one. It means, make this field non-editable, preserved, or smth like that. Making it CharField or just Field will not help here, I think, because I need an object from this field later for validation and processing. Can someone, please, help?
self.fields['field_name'].widget.attrs['readonly'] = True
Turned out, I needed here the following code:
self.fields['field_name'].widget.attrs['disabled'] = 'disabled'
This option will remove the instance from the form fields when you submit the form.
self.fields['field_name'].widget.attrs['disabled'] = 'disabled'
Using this option you will disable de field to be edited and you can converse the init instance to be saved into the database.
algorithm = forms.ModelChoiceField(label='Algoritmo',queryset=Algorithm.objects.all(),to_field_name="name",widget=forms.TextInput(attrs={'readonly':'readonly'}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With