2010-06-04 52 views
4

我有一個需要有一個有效的URL或上載一個有效的文件形式:你如何讓Django表單驗證動態?

class ResourceUpload(ModelForm): 
    ...   
    uploadedfile = forms.FileField('file') 
    url_address = forms.URLField('url') 
    ... 

我如何可以覆蓋FileFieldURLField驗證,使Django只產生一個錯誤上面這兩種領域是無效的,但除非一方無效,只要另一方有效?

回答

7

你需要將它們既作爲required=False,所以數據庫後端並不需要他們兩個填充,然後使用form cleaning

import forms 

class ResourceUpload(ModelForm): 
    ...   
    uploadedfile = forms.FileField(required = False, upload_to='put/files/here') 
    url_address = forms.URLField(required = False) 
    ... 

    def clean(self): 
     cleaned_data = self.cleaned_data 
     uploadedfile = cleaned_data.get("uploadedfile ") 
     url_address = cleaned_data.get("url_address ") 

     if not uploadedfile and mot url_address : 
      raise forms.ValidationError("Provide a valid file or a valid URL.") 

     return cleaned_data   
7

我的解決方案
優點:它使星號對於真正需要的領域和默認錯誤信息

class Form(forms.ModelForm): 
    field1 = SelectField 
    field2 = ... 
    field3 = ... 

    def __init__(self, *args, **kwargs): 
     super(Form, self).__init__(*args, **kwargs) 
     if kwargs['data']: 
      if kwargs['data'].get('field1') == '1': 
       self.fields['field2'].required = True 
       self.fields['field3'].required = False 
      elif kwargs['data'].get('field1') == '2': 
       self.fields['field2'].required = False 
       self.fields['field3'].required = True 
4

這裏是我的解決方案,真正的作品...(測試)

def __init__(self, *args, **kwargs): 
    super(YourForm, self).__init__(*args, **kwargs) 

    if self.data and self.data.get('field_name') != 'SOMETHING': 
     self.fields.get('field_name2').required = True 

如果field_name的輸入不是'SOMETHING',這將使field_name2成爲必填字段。 Django岩石!

+0

Django真的很棒! – 2017-01-16 01:44:22