python - 将 Django 所需的表单字段更改为 False

标签 python django forms

我正在尝试根据另一个字段的输入将表单字段的要求更改为“False”。

形式:

class MyNewForm(forms.Form):

def __init__(self, *args, **kwargs):
    self.users = kwargs.pop('users', None)
    super(MyNewForm, self).__init__(*args, **kwargs)


    self.fields['name'] = forms.CharField(
        max_length=60,
        required=True,
        label="Name *:",
        widget=forms.TextInput(
            attrs={'class' : 'form-control', 'placeholder': 'Name'})
    )

def clean_this_other_field(self):

    # change required field
    name = self.fields['name']
    print name.required
    name.required=False
    print name.required

打印结果:

正确

错误

因此所需的字段正在更改为“False”,但是当表单页面重新加载时它恢复为“True”

有什么建议吗?

EDIT - Problem solved

对于任何遇到类似问题的人:

def clean_remove(self):
    cleaned_data = super(MyNewForm, self).clean()
    remove = cleaned_data.get('remove', None)
    if remove:
        self.fields['name'].required=False

删除是表单中的第一个字段,因此在删除字段上添加这个 clean 可以解决问题。

最佳答案

当这个问题出现时,你能提供更多你的代码吗?

如果您使用 ModelForm,您可以执行以下操作:

class YourForm(forms.ModelForm):    
    def __init__(self, *args, **kwargs):
        super(YourForm, self).__init__(*args, **kwargs)
        self.fields['name'].required = True

    class Meta:
        model = YouModel
        fields = (...)

Django Model Forms - Setting a required field

您也可以使用小部件添加所需的内容:

email = forms.EmailField(
    max_length=100,
    required=True,
    widget=forms.TextInput(attrs={ 'required': 'true' }),
)

关于python - 将 Django 所需的表单字段更改为 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46094811/

相关文章:

Django:urls.py 中的 urlpatterns 格式

javascript - 如何禁用大表单中的特定表单元素

jquery - 停止在 Internet Explorer 中提交表单

python - chaquopy代码在什么目录下查找Android应用代码的Python代码中导入的Python包

python - 为什么 np.array([1, "a"]) 消耗 21 个字符的 Unicode 字符串?

python - 将字符串列表转换为数字列表而不指定 int 或 float

python - 如何在 mac 上将 openalpr 与 python 绑定(bind)?

Django 用户组仅用于权限?

django - Django 上的 Facebook 积分回调

forms - 如何增加子网格中的行高