如何使char字段表现得像django中的URLField



我正在使用Django,我想要一个URL字段。我知道Django中有一个URLField,但我希望该字段是一个charfield,我不希望用户在该charfield 中提交URL以外的任何内容

看看我的模型。py:

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email = models.EmailField(max_length=500, blank=True, null=True)
social_github = models.CharField(max_length=200, blank=True, null=True)
social_twitter = models.CharField(max_length=200, blank=True, null=True)
social_linkedin = models.CharField(max_length=200, blank=True, null=True)
social_youtube = models.CharField(max_length=200, blank=True, null=True)
social_website = models.CharField(max_length=200, blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(
default=uuid.uuid4, unique=True, primary_key=True, editable=False)
def __str__(self):
return str(self.username)

请回答如何使字符字段表现得像URL字段

URLField本质上只是一个经过验证的CharField(默认名称默认为URL(的翻译(,最大长度为200。事实上,如果我们查看源代码[GitHub],我们会看到:

class URLField(CharField):
default_validators = [validators.URLValidator()]
description = _("URL")
def __init__(self, verbose_name=None, name=None, **kwargs):
kwargs.setdefault('max_length', 200)
super().__init__(verbose_name, name, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
if kwargs.get("max_length") == 200:
del kwargs['max_length']
return name, path, args, kwargs
def formfield(self, **kwargs):
# As with CharField, this will cause URL validation to be performed
# twice.
return super().formfield(**{
'form_class': forms.URLField,
**kwargs,
})

它还使用了一个不同的形式字段:URLField是[实现为[GitHub]]:

class URLField(CharField):
widget = URLInput
# …

因此它将使用URLInput小部件,但没有什么可以阻止您使用另一个小部件。事实上,我们可以用来实现该模型

class Profile(models.Model):
# …
social_github = models.URLField(blank=True, null=True)
social_twitter = models.URLField(blank=True, null=True)
social_linkedin = models.URLField(blank=True, null=True)
social_youtube = models.URLField(blank=True, null=True)
social_website = models.URLField(blank=True, null=True)
# …

如果您想更改小部件,例如在ModelForm中,您可以使用:

class MyProfileForm(forms.ModelForm):
# …
class Meta:
# …
widgets = {
'social_github':forms.TextInput,
'social_twitter':forms.TextInput,
'social_linkedin':forms.TextInput,
'social_youtube':forms.TextInput,
'social_website':forms.TextInput
}

最新更新