我们想在保存用户进入数据库之前做一些字段的校验,先贴出代码;

import re
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver

UNAME_REG = re.compile(r"^\w*")
DATE_REG = re.compile(r"(19\d{2})|(20\d{2})-(0[1-9])|(1[1-2])-(0[1-9])|([12][0~9])|(3[0-1])")

class User(models.Model):
    name = models.CharField(max_length=32)
    birthday = models.DateField()
    gender = models.BooleanField(default=True)
    desc = models.CharField(max_length=256)
    is_active = models.BooleanField(default=True)


logger = logging.getLogger(__name__)
 
@receiver(pre_save, sender=User)
def pre_save_handler(sender, **kwargs):
    
    logger.debug("{},{}".format(sender, **kwargs))
    if not re.match(UNAME_REG, kwargs.uname):
     logging.error("username has error!") return if not re.match(UNAME_REG, kwargs.udate):
     logging.error("birthday has error!") return

signals.py 文件在 django.db.models.signals,以下是部分源码

 

from django.apps import apps
from django.dispatch import Signal
from django.utils import six


class_prepared = Signal(providing_args=["class"])


class ModelSignal(Signal):

# Model初始化之前
pre_init = ModelSignal(providing_args=["instance", "args", "kwargs"], use_caching=True)
# Model初始化之后
post_init = ModelSignal(providing_args=["instance"], use_caching=True)
# Model调用save之前,可以做一些验证之类的操作
pre_save = ModelSignal(providing_args=["instance", "raw", "using", "update_fields"], use_caching=True)
# Model保存之后,可以添加一些任务,关联验证这些
post_save = ModelSignal(providing_args=["instance", "raw", "created", "using", "update_fields"], use_caching=True)
# Model调用删除之前
pre_delete = ModelSignal(providing_args=["instance", "using"], use_caching=True)
# Model调用删除之后,可以做删除一些关联数据,关联任务之类的操作
post_delete = ModelSignal(providing_args=["instance", "using"], use_caching=True)
# 关联数据发生变化时
m2m_changed = ModelSignal(providing_args=["action", "instance", "reverse", "model", "pk_set", "using"], use_caching=True)
# 改变模型
pre_migrate = Signal(providing_args=["app_config", "verbosity", "interactive", "using"])
post_migrate = Signal(providing_args=["app_config", "verbosity", "interactive", "using"])
# 同步数据,创建数据表
pre_syncdb = Signal(providing_args=["app", "create_models", "verbosity", "interactive", "db"])
post_syncdb = Signal(providing_args=["class", "app", "created_models", "verbosity", "interactive", "db"])

Django==1.7.7