簡體   English   中英

為什么在定義 model CharField 時使用 validators=[URLValidator] 不會在保存相應的 ModelForm 時檢查 URL 有效性?

[英]Why using validators=[URLValidator] when defining a model CharField doesn't make it check for URL-validity upon saving the corresponding ModelForm?

app.models.py:

from django.core.validators import URLValidator
from django.db import models

class Snapshot(models.Model):
    url = models.CharField(max_length=1999, validators=[URLValidator])

app.forms.py:

from django import forms
from .models import Snapshot

class SnapshotForm(forms.ModelForm):
    class Meta:
        model = Snapshot
        fields = ('url',)

app.views.py:

from django.http import HttpResponse
from .forms import SnapshotForm

def index(request):
    snapshot_form = SnapshotForm(data={'url': 'not an URL!'})

    if snapshot_form.is_valid():
        snapshot_form.save()

    return HttpResponse("")

為什么它將“不是 URL”保存到 DB 中? 盡管它不是一個有效的 URL?!

合並URLValidator的正確方法是什么?

您已經為您的字段指定了驗證器,如下所示: validators=[URLValidator] 這是不正確的,因為validators參數包含執行驗證的可調用列表。 在這種情況下,即使URLValidator是可調用的,但這實際上是被調用的 class 的__init__方法。 您需要傳遞 class 的實例才能使其正常工作:

# Note the brackets after URLValidator to instantiate the class
url = models.CharField(max_length=1999, validators=[URLValidator()])

更好的是,因為你想輸入一個 URL 你應該簡單地使用URLField class你的領域:

url = models.URLField(max_length=1999)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM