3

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
Vladimir
  • 103
  • 2
  • 8
  • 1
    Please show the code for your ModelForm and describe what behavior you see and what you're expecting to see. – dylrei Feb 02 '15 at 17:59
  • show some code... but based on your information the only thing I could possibly assume is that you must do this kind of setting on your template instead on your models.py you can see this already been answered here.. see if it works for you http://stackoverflow.com/questions/2933478/mandatory-read-only-fields-in-django – Eddwin Paz Feb 02 '15 at 18:26
  • 2
    Why even display the field if you are only going to use the default value? You don't need to POST the value in order to be able to use it in your Python code, you can simply access it from the model. – Brandon Taylor Feb 02 '15 at 18:30
  • Not exactly sure what you want to achieve, but can you use the fields.editable attribute something on the lines of in your models. ` myField = models.CharField(editable=False)` or in the modelForm just exclude the field like ` class Meta: model = myModel exclude = ('myField')` – cmidi Feb 02 '15 at 18:52
  • Well, the point is that in some cases, depending on the user's data, we need to forbid him/her to select value in this field and in some cases we must allow to do that. Thanks everyone, problem was solved. The solution is based on the information from @eddwinpaz comment. – Vladimir Feb 04 '15 at 10:06

2 Answers2

2

Turned out, I needed here the following code:

self.fields['field_name'].widget.attrs['disabled'] = 'disabled'
Vladimir
  • 103
  • 2
  • 8
1

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'}))
Aurelio Vivas
  • 56
  • 1
  • 3