[英]What is the best, cleanest and shortest way to check if a given value is valid URL when working with models?
I rather want to use Django's built-in functionalities as much as possible and avoid implementing stuff myself as much as possible!我宁愿尽可能多地使用 Django 的内置功能,并尽可能避免自己实现东西!
Why doesn't the following code issue exceptions when given a non-URL value?为什么以下代码在给定非 URL 值时不发出异常?
models.py :模型.py :
from django.core.validators import URLValidator
from django.db import models
class Snapshot(models.Model):
url = models.URLField(validators=[URLValidator])
views.py :视图.py :
from django.http import HttpResponse
from .models import Snapshot
def index(request):
a = Snapshot(url='gott ist tot')
a.save()
Because this validator is run when you use a django form.因为此验证器在您使用 django 表单时运行。 More information about validators on the doc: https://docs.djangoproject.com/en/4.1/ref/validators/
有关文档验证器的更多信息: https://docs.djangoproject.com/en/4.1/ref/validators/
if you do a form:如果你做一个表格:
from django import forms
from .models import Snapshot
class SnshotForm(forms.ModelForm):
class Meta:
model = Snapshot
fields = ('url', )
and your views.py:和你的views.py:
from django.http import HttpResponse
from .forms import SnapshotForm
def index(request):
a = SnapshotForm(data={'url': 'gott ist tot'})
if a .is_valid()
a.save()
else:
print(a.errors)
Your validator will be run and you will see the errors form message您的验证器将运行,您将看到错误表单消息
Without using form, you can call manually validator in your view or in the save method:在不使用表单的情况下,您可以在视图或保存方法中手动调用验证器:
# in views
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
def index(request):
url_validator = URLValidator()
url = 'gott ist tot'
is_valid_url = False
try:
url_validator(url)
except ValidationError:
pass
if is_valid_url:
a = Snapshot(url=url)
a.save()
else:
print(a.errors)
Be careful, I do not recommanded to bypass the validator with forms, i think it is the better way for maximizing usage of django builtins funtions小心,我不建议使用表单绕过验证器,我认为这是最大化使用 django 内置函数的更好方法
You can check if a URL is a valid URL by using URL Validator.您可以使用 URL 验证器检查 URL 是否是有效的 URL。
from django.core.validators import URLValidator
from django.db import models
class Snapshot(models.Model):
url = models.URLField(validators=[URLValidator])
In addition, if you want to check if is URL is accessible or not, you can do something like that in clean_url
or in view
like that:此外,如果您想检查 URL 是否可访问,您可以在
clean_url
或view
中执行类似操作:
import urllib.request
def clean_url(self):
try:
urllib.request.urlopen(self.cleaned_data['url']).getcode()
except:
raise forms.ValidationError('Invalid URL')
return self.cleaned_data['url']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.