django urlfield http前缀 [英] django urlfield http prefix

查看:90
本文介绍了django urlfield http前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何摆脱Django urlfield中的'http://'前缀吗?

Does any one know how to get rid of the 'http://' prefix in Django urlfield.

我的意思是当我们将字段定义为urlfield并尝试要输入网址,如果没有提供任何架构,django会自动在其中添加 http://前缀。我不想要该前缀。

I mean when we define a field as urlfield and try to enter a url to it, django will automatically add 'http://' prefix to it if no schema provide. I don't want that prefix.

我尝试在clean_field和clean方法下将其删除。

I try to remove it under clean_field and clean method. It doesn't work.

我深入研究了源代码。我看到django在UrlField类下的 to_python方法中添加了 http://。

I dig into the source code. I saw that django add 'http://' in 'to_python' method under UrlField class.

有什么方法可以覆盖它来摆脱 http:/ /'?

Is there any way to override it to get rid of 'http://'?

推荐答案

没有方案前缀,字符串不能是真实的URL,因此, URLField 不支持。

Without a scheme prefix, a string can't be a true URL, and accordingly, the URLField won't support it.

但是, URLField 几乎只是一个 CharField URLValidator ,因此,如果您编写一个新的 SchemelessURLValidator (源自内置的),然后添加到普通的 CharField ,应该可以将您带到想要去的地方。

However, the URLField is pretty much just a CharField with a URLValidator, so if you write a new SchemelessURLValidator (derived from the built-in one) and add that to a normal CharField, that should get you where you want to go.

实际上,您的新验证程序可以就像

In fact, your new validator could be as simple as

class SchemelessURLValidator(URLValidator):
    regex = re.compile(
    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)

这篇关于django urlfield http前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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