Django自定义字段验证器与清理 [英] Django custom field validator vs. clean

查看:58
本文介绍了Django自定义字段验证器与清理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建TodayOrLaterDateField(),该类将继承DateField()字段,因为我在许多地方都使用此条件。该字段的目的是避免放置过去的日期。

I would like to create TodayOrLaterDateField() which would subclass DateField() field as I am using this condition in many places. The purpose of this field would be avoiding putting dates from the past.

最直接的方法是什么?我对验证器与清理方法感到困惑。
我尝试使用clean(),但是将值与datetime.date.today()比较时,出现比较unicode对象与日期错误。

What is the most straightway way of doing this? I am confused with validator vs. clean method. I've tried with clean() but when comparing value to datetime.date.today() I am getting "compare unicode object to date" error.

我正在使用Django 1.3

I'm using Django 1.3

推荐答案

验证程序仅进行验证,他们没有返回改进的格式;
清洁方法会验证并返回(有时会被修改)值。

Validators only validate, they don't return the improved format; Clean methods both validate and return a (sometimes amended) value.

我认为这里的方法是将带有验证器的DateField用作

I think the way to go here is to just use a DateField with a validator as a inherited class of DateField with a default_validators set.

import datetime
from django.core import exceptions
from django.db import models
from django.utils.translation import ugettext_lazy as _

def validate_date_today_or_later(value):
    'Place this in validators.py and import it to keep your model a bit cleaner'
    if value < datetime.date.today():
        raise exceptions.ValidationError(_('Date must be today or later'))

class TodayOrLaterDateField(models.DateField):
    default_validators = [validate_date_today_or_later,]

编辑:
您可以将相同的验证器应用于表单字段同样,如果您只是想在这里而不是在整个应用中使用它。

edit: You can apply the same validator to your form fields as well if you just want it there and not in your whole app.

这篇关于Django自定义字段验证器与清理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆