2017-09-07 29 views
0

我试图根据另一个字段的输入将所需的表单字段更改为'False'。将Django所需的表单字段更改为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 

打印的结果:

因此所需的字段被更改为 '假',但是当表单页面重新加载它恢复为'真'

有什么建议吗?

编辑 - 问题解决

对于任何降落在这个有一个类似的问题:

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

删除是如此添加此干净的删除字段解析形式的第一场问题。

+0

你可能需要ID都字段放在你的模板中,并使用Javascr更新依赖项的'required'属性IPT。依赖字段可以被设置为非必需的,或者为其确定强制的服务器端。 –

+0

我不明白你为什么认为这不会发生。当然,重新加载会导致字段恢复为True;你的'__init__'将它设置为True,所以它*必须*总是这样做。你还期望什么? –

+0

真的不是一个有用的评论......我没有说我没有想到会发生这种情况,我问是否有任何建议来阻止这种情况的发生。 – drew

回答

0

当出现此问题时,您可以提供更多代码吗?

如果妳使用的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

U可以加用必需的部件也:

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

我已经添加了一些我的表单 – drew

+0

我正在使用表单自己的必需属性,但问题是在提交后改变它并取决于其他字段,保持它的方式 – drew

+0

尝试添加必需的部件。我将它添加到我的答案中。 – Thaian

相关问题