Reputation: 103
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
Upvotes: 3
Views: 3290
Reputation: 86
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'}))
Upvotes: 1
Reputation: 103
Turned out, I needed here the following code:
self.fields['field_name'].widget.attrs['disabled'] = 'disabled'
Upvotes: 2