我試圖根據另一個字段的輸入將所需的表單字段更改爲'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
刪除是如此添加此乾淨的刪除字段解析形式的第一場問題。
你可能需要ID都字段放在你的模板中,並使用Javascr更新依賴項的'required'屬性IPT。依賴字段可以被設置爲非必需的,或者爲其確定強制的服務器端。 –
我不明白你爲什麼認爲這不會發生。當然,重新加載會導致字段恢復爲True;你的'__init__'將它設置爲True,所以它*必須*總是這樣做。你還期望什麼? –
真的不是一個有用的評論......我沒有說我沒有想到會發生這種情況,我問是否有任何建議來阻止這種情況的發生。 – drew