python - django禁用Booleanfield未在POST方法上提交

标签 python django django-forms django-views

我有一个 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 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.

我建议更新表单类的 __init__() 方法,以便仅在要禁用该字段时添加 disabled 属性。

关于python - django禁用Booleanfield未在POST方法上提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56495676/

相关文章:

python - 无法通过 pip 在 Python 上安装 pygame (Windows 10)

Django Filter 查询 - 如果参数为空则忽略

python - Django Rest Framework 实例化序列化器错误

python - Django 和 Deployment 中的私有(private)设置

python - Django objects.all() 空查询集,在 shell 中不为空

python - OpenCV 和 Python 中直线的反射

Python 检查将方法识别为 FunctionType 而不是 types.MethodType

python - Django 模型表单设置 POST 但不保存

mysql - 处理 Django form.save() ValueError

django - 使用现有的 django.contrib.auth.forms 实现 Django Simple Captcha