我有一个 BooleanField,在特定条件下需要禁用。
即使已禁用,我如何提交输入
first time form submit
second time form submit忽略禁用的 bool 字段
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})
每次禁用的 BooleanField 都会返回 false,即使它被选中
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')
最佳答案
这是 Django 有意设计的决定,以便用户无法编辑 HTML 输入并删除 disabled
属性,这可能使用户能够更新他们不打算更新的值。来自 docs :
The
disabled
boolean argument, when set toTrue
, disables a form field using thedisabled
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.
我建议更新表单类的 __init__()
方法,以便仅在要禁用该字段时添加 disabled
属性。
关于python - django禁用Booleanfield未在POST方法上提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56495676/