10

I'd like to create disabled field with ModelForm on django 1.11.

I read django has "disabled field options" since 1.9. However, I can not understand how do I define disabled field with ModelForm.

Could you tell me how to create disabled field with ModelForm please ?

Here is my models.py, forms.py and views.py


class my_model(models.Model)

    name = models.CharField(max_length=10,)
    title = models.CharField(max_length=10,)
    date = models.DateField(default=date.today,)

    def __str__(self):
        return u'%s' % (self.name)

class my_modelform(ModelForm):

    class Meta:
        model = my_model
        fields = ['name', 'title', 'date']
        widgets = {
            'date': DateWidget(usel10n=True, bootstrap_version=3,),
        }
        disabled = [ 'name' ]

class my_UpdateView(UpdateView):
    model = my_model
    form_class = my_modelform
    template_name = "update_form.html"
    success_url = "success.html"    

Although, I changed the "disabled = {'name' : True} instead of [ 'name' ], it doesn't work.

Akira Inamori
  • 109
  • 2
  • 5

1 Answers1

17
class Meta:
    model = my_model
    fields = ['name', 'title', 'date']
    widgets = {
        'date': DateWidget(usel10n=True, bootstrap_version=3,),
        'name': forms.TextInput(attrs={'disabled': True}),
    }
nik_m
  • 11,825
  • 4
  • 43
  • 57
  • 1
    Thank you so much. I did it – Akira Inamori Mar 13 '17 at 19:53
  • Glad I could help. If the answer helped you, mark it as accepted and happy coding! – nik_m Mar 13 '17 at 19:55
  • It worked, but the disabled options filed will miss the value when I submit. – Akira Inamori Mar 13 '17 at 20:47
  • Of course it will miss it since it is disabled! How you pass that value? – nik_m Mar 13 '17 at 20:51
  • Oh, I thought "disable" means that the field can not edit. not remove the column. My goal is that there is only one or two field can be editable when I use UpdateView. Therefore, I want the rest fields switch uneditable field. – Akira Inamori Mar 13 '17 at 20:59
  • If I understand correclty, what you asked is feasible via Javascript. The original question was to make a `ModelForm` field, `disabled`. – nik_m Mar 13 '17 at 21:02
  • Yes, the original question is "Make a disabled field with ModelForm" I should have asked that what I want to do, because the feature did not same as that I thought.... I really appreciate your great help. – Akira Inamori Mar 13 '17 at 21:11
  • Hmm. Then glad once again I could help. In your next question be more specific please! – nik_m Mar 13 '17 at 21:13
  • 1
    I changed "attrs={'readonly': True}" instead of "attrs={'disabled': True}", then it works as expected. – Akira Inamori Mar 13 '17 at 21:21
  • That's great news! Although your question asked another thing... Anyway, take care my friend. – nik_m Mar 13 '17 at 21:22
  • This is awesome, works for all sorts of field. Also works for enforcing all type of inputfield – Shamsul Arefin Jun 17 '19 at 08:02