Vladimir
Vladimir

Reputation: 103

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

Upvotes: 3

Views: 3290

Answers (2)

Aurelio Vivas
Aurelio Vivas

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

Vladimir
Vladimir

Reputation: 103

Turned out, I needed here the following code:

self.fields['field_name'].widget.attrs['disabled'] = 'disabled'

Upvotes: 2

Related Questions