使用自定义验证覆盖URLField的验证

8 投票
3 回答
4798 浏览
提问于 2025-04-17 21:55

我想知道怎么用自定义的验证方法来替换Django中URLField的验证?这个操作应该在哪里进行呢?

我希望它能接受没有域名后缀的URL。

3 个回答

0

你可以试试用一个字符字段(CharField,URL字段的父类)配上你自己的验证器。

如果需要的话,可以看看这个例子,希望对你有帮助。谢谢!

2

你可以在你的模型中创建自定义的正则表达式验证,或者使用Django提供的URL验证。

选项1:

from django.core.validators import RegexValidator
URL_VALIDATOR_MESSAGE = 'Not a valid URL.'
URL_VALIDATOR = RegexValidator(regex='/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/', message=URL_VALIDATOR_MESSAGE)


class SocialAccounts(models.Model):
    user = models.ForeignKey("Profile", on_delete=models.CASCADE, blank=True, null=True, unique=True)
    facebook = models.URLField(max_length=200, null=True, blank=True, validators=[URL_VALIDATOR])

选项2:

from django.core.validators import URLValidator
class OptionalSchemeURLValidator(URLValidator):
    def __call__(self, value):
        if '://' not in value:
            # Validate as if it were http://
            value = 'http://' + value
        super(OptionalSchemeURLValidator, self).__call__(value)


class SocialAccounts(models.Model):
    user = models.ForeignKey("Profile", on_delete=models.CASCADE, blank=True, null=True, unique=True)
    facebook = models.URLField(max_length=200, null=True, blank=True, validators=[OptionalSchemeURLValidator])
    instagram = models.URLField(max_length=200, null=True, blank=True,
                                validators=
                                    [RegexValidator(
                                        regex= '/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/',
                                        message='Not a valid URL',
                                    )])
7

这是Django的网址字段验证器。你可以给它提供一个自定义的正则表达式myregex。不过,你需要关闭UrlField的默认验证,因为这不是你想要的。

所以你可以这样创建一个自定义字段:

然后在你的模型或表单中,像这样给字段提供这个:

from django.forms import UrlField as DefaultUrlField
class UrlField(DefaultUrlField):
    default_validators = [URLValidator(regex=myregex)]

接着在你的表单中,只需要这样做:

my_url_field = UrlField()

撰写回答