Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django make ModelChoiceField non-editable

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
like image 684
Vladimir Avatar asked Jan 23 '26 11:01

Vladimir


2 Answers

Turned out, I needed here the following code:

self.fields['field_name'].widget.attrs['disabled'] = 'disabled'
like image 131
Vladimir Avatar answered Jan 26 '26 01:01

Vladimir


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'}))
like image 31
Aurelio Vivas Avatar answered Jan 26 '26 02:01

Aurelio Vivas