2015-05-02 43 views
0

我爲我的一個模型使用DateTimeField。它有一個custom validator,檢查,沒有日期將被接受。如何顯示Django管理員中的DateTimeField的自定義驗證錯誤?

如果我提供的日期在將來,錯誤會正確提出,但管理員顯示Bitte eine Liste mit Werten eingeben.Enter a list of values.)而不是我的驗證錯誤消息。

我怎樣才能讓管理員顯示我自己的驗證錯誤信息呢?

這裏是我的自定義驗證(full source in this gist)的相關部分:

@deconstructible 
class DateValidator(): 

    # … 

    def __call__(self, value): 
    """ 
    Check *value* against the stored *date*. 

    If *date* is callable, it's return value is used, if not, it is used 
    directly. 

    """ 
    # get min/max date 
    try: 
     date = self.date() 
    except TypeError: 
     date = self.date 
    # check 
    if self.equal and value == date: 
     return 
    if self.after: 
     if value > date: 
     return 
    else: 
     if value < date: 
     return 
    raise ValidationError(
     self.message, code='invalid', params={ 
     'value': value.strftime(self.DATETIME_FORMAT), 
     'date': date.strftime(self.DATETIME_FORMAT) 
     } 
    ) 

我用它是這樣的:

@python_2_unicode_compatible 
class Article(models.Model): 

    # … 

    pub_date = models.DateTimeField(
    'Veröffentlichungsdatum', blank=True, null=True, 
    validators=[DateValidator(timezone.now)], 
    help_text=("…") 
) 
+0

將相關代碼添加到帖子中wo uld有助於調試,特別是你如何調用驗證器。 – Wolph

回答

1

可以在forms.py 提高forms.ValidationError以下是一個示例:

class LoginForm(forms.Form): 
    username = forms.CharField() 
    password = forms.CharField(widget=forms.PasswordInput()) 

    def clean_username(self): 
     username = self.cleaned_data.get("username") 
     try: 
      user = User.objects.get(username=username) 
     except User.DoesNotExist: 
      raise forms.ValidationError("Are you sure you are registered? We cannot find this user.") 
     return username 
+0

謝謝,但我寧願在模型(定義)上設置我的驗證器。有沒有辦法創建一個自定義窗體,只是爲了顯示我的'ValidationError'的消息? – Brutus

+0

如果我沒有誤解你說的話:你想要一個自定義表單來顯示驗證錯誤。如果是這樣,我們剛剛做到了。 LoginForm是一個自定義窗體,僅顯示驗證錯誤。 – user248884

+0

這就是我所不需要做的。我創建了一個自定義驗證器,並將其用於我的**模型定義**(而不是定製表單) - 並且它可以工作。問題是:在Django管理員中,不是來自驗證程序的消息,而是顯示了一條不同的錯誤消息,儘管識別出了「ValidationError」。 – Brutus

相關問題