我正在使用django 1.7 & python 2.7。django python動態max_length基於選擇列表值
我有一個模型類,它允許用戶的文本區域和文本框輸入。
If
用戶在選擇列表中選擇0,then
文本框被顯示給用戶,用於輸入和文本區域被隱藏else
顯示文本區域並從用戶隱藏的文本框中。
文本框和文本區域都有完全相同的輸入。在文本框中輸入什麼都會出現在文本區域,反之亦然。
文本框和文本區域都有不同的maxlength/max_length值。
文本框有250的最大長度和文本區域有5000
我有客戶端驗證工作的最大長度,但我有困難得到服務器端驗證工作。
當文本框和文本區域具有不同的max_length值,但輸入長度相同時,如何在forms.py文件中啓用/禁用服務器端驗證模型?
據我所知,max_length可以在forms.py上賦值,但是我無法獲得正確的代碼語法。
這裏是我的models.py代碼:
workplace_training_display_type = models.PositiveIntegerField(.....)
workplace_training_certificationTB = models.CharField(null=False, blank=False)
workplace_training_certificationTA = models.TextField(null=False, blank=False)
通常我會掉落max_length=250
到workplace_training_certificationTB
和max_length=5000
到workplace_training_certificationTA
上述模型領域。不過,我相信這必須在forms.py文件中動態完成。
編輯 如果我設置了MAX_LENGTH針對的是workplace_training_certificationTB
和workplace_training_certificationTA
的車型,因爲這兩個領域具有完全相同的輸入,那麼將觸發服務器端驗證的一個,這就是爲什麼我想動態設置值。
這裏是我的forms.py文件代碼:
def clean(self):
cd_wrtdf = super(WorkplaceRelatedTrainingDetailsForm, self).clean()
if 'workplace_training_display_type' in cd_wrtdf and cd_wrtdf['workplace_training_display_type'] != 0:
# if the workplace_training_display_type is not zero, remove the max_length=250 from the textbox.
# if the workplace_training_display_type is not zero, add the max_length=5000 to the textarea.
else:
# if the workplace_training_display_type is zero, add the max_length=250 to the textbox.
# if the workplace_training_display_type is zero, remove the max_length=5000 from the textarea.
return cd_wrtdf
我試圖尋找SO &谷歌,但找不到任何幫助。
爲什麼不在服務器上使兩個字段的長度相同? –
dan-klasson - 因爲如果兩個字段的輸入長度相同並且文本區域有1000個字符,則會觸發文本框的服務器端驗證最大長度(250個字符)。 – user3354539
@ user3354539如果您在模型級別設置max_length,則django會自動驗證您要求的內容 – Alvaro