2

I have a BooleanField that given certain conditions, needs to be disabled.

How can I submitting the input even if it's disabled

first time form submit
second time form submit that ignore disabled booleanfield

views.py

def test(request):
    form = InformationForm()
    test_table = TestTable.objects.get(id=1)
    result = ''

    if test_table.status == True:
        result = True
        form.fields['agree'].initial = True    
        form.fields['agree'].widget.attrs['disabled'] = True
        # form.fields['agree'].widget.attrs={'onclick': 'return false','style':'opacity: 0.4 !important'}

    if request.method == "POST":
        post_form = InformationForm(request.POST)
        result = post_form['agree'].value()
        text = post_form['text'].value()

        if post_form['agree'].value() == True:
            t = TestTable.objects.filter(id=1).first()
            t.status = 1
            t.save()

            post_form.fields['agree'].initial = True  
            post_form.fields['agree'].widget.attrs['disabled'] = True
           #post_form.fields['agree'].widget.attrs={'onclick': 'return false','style':'opacity: 0.4 !important'}
            return render(request,'test.html',context={'form':post_form,'result':result,'text':text})

    text = form['text'].value()
    return render(request,'test.html',context={'form':form,'result':result})

every time disabled BooleanField returns false, even it selected
i am also referred this link

forms.py

class InformationForm(forms.Form):
    text = forms.CharField(max_length=50)
    agree = forms.BooleanField(required=False)

    def clean(self):
        agree = self.cleaned_data.get('agree')
        text = self.cleaned_data.get('text')

    #def clean_agree(self):
    #    if self.instance and self.instance.pk:
    #        return self.instance.agree
    #    else:
    #        return self.cleaned_data.get('agree')
ArunKumar
  • 179
  • 1
  • 1
  • 11
  • you should set disabled on the field, not on the widget (`post_form.fields['agree'].disabled = True`) and you should not use the `value()` of a field but the actual `cleaned_data`: `if form.is_valid(): result = form.cleaned_data['agree']`. – dirkgroten Jun 07 '19 at 14:14

1 Answers1

3

This is an intentional design decision by Django so that users can't edit the HTML input and remove the disabled attribute, which could enable users to update values they aren't meant to update. From the docs:

The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users. Even if a user tampers with the field’s value submitted to the server, it will be ignored in favor of the value from the form’s initial data.

I recommend updating your form class's __init__() method so that it only adds the disabled attribute when the field is meant to be disabled.

Community
  • 1
  • 1
Franey
  • 4,164
  • 2
  • 16
  • 18