我想获取与模型字段对应的所有正则表达式(验证器)以将它们传递给javascript(以在客户端进行验证)。
但是我可以使用所有验证器,但验证器在验证器中没有正则表达式字段.__ dict __ :
# from django.core.validators, URLValidator
class URLValidator(RegexValidator):
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
message = _('Enter a valid URL.')
def __call__(self, value):
... # and so on
试图收集models.URLField的正则表达式的代码:
def get_regexes( model_obj, name ):
field = model_obj._meta.get_field_by_name( name )[ 0 ]
# A list of all validators
validators = field.validators
# Each validator can have attrs: 'regex', or '<some>_regex'
for valid in validators:
print "# valid={0}".format( valid ) # the dict has not regex field
print "# valid_dict={0}".format( valid.__dict__ ) # the dict has not regex field
obj_fields = valid.__dict__
regexes = []
if 'regex' in obj_fields:
regexes.append( obj_fields.regex )
# check if there are another regexes
for key, val in obj_fields.iteritems():
if '_regex' in key:
regexes.append( obj_fields[ key ] )
return regexes
print get_regexes( User, 'url' )
'url是User模型类中的常用URLField:
class User(AbstractBaseUser):
email = models.EmailField(unique=True, db_index=True)
name = models.CharField(max_length=64, db_index=True)
surname = models.CharField(max_length=64, db_index=True)
lname = models.CharField(max_length=64, db_index=True) # Отчество
url = models.URLField()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
class Meta:
db_table = 'user'
所以,我的代码输出:
# valid=<django.core.validators.URLValidator object at 0x0202AB70>
# valid_dict={}
# valid=<django.core.validators.MaxLengthValidator object at 0x02158670>
# valid_dict={'limit_value': 200}
我看到验证器对象,但我无法知道属性regex在哪里(在URLValidator的代码中)。
答案 0 :(得分:0)
为什么还要编写服务器端代码来执行此操作?如果要在浏览器中验证URL,请在浏览器中编写代码以验证URL。