Reputation: 23169
I am using a subclassed Django URLField to perform some validation on clicked URLs. I added mailto as one of the supported URLValidator default_validators:
class MyURLField(forms.URLField):
default_validators = [
validators.URLValidator(
schemes=['http', 'https', 'ftp', 'ftps', 'mailto']
)
]
class MyForm(forms.Form):
url = MyURLField(required=True)
form = MyForm({'url': 'mailto:[email protected]'})
if not form.is_valid():
raise Exception()
clean_url = form.cleaned_data['url']
print(clean_url) # this prints 'mailto://[email protected]'
Is a mailto
URL still valid with the two extra protocol slashes?
mailto:[email protected]
versus mailto://[email protected]
(what Django produces)
Upvotes: 2
Views: 624
Reputation: 12859
Django has an EmailField
so if you want to store email addresses, or even use them in forms, use these fields because you get the built-in validation and don't have to hack anything like you're going to have to with your approach.
In your models you'd do;
class MyModel(models.Model):
email = models.EmailField(
verbose_name=_('Email'),
max_length=255,
unique=True,
db_index=True
)
In your forms it's very similar;
class MyForm(forms.ModelForm):
email = forms.EmailField(
label=_("Email")
)
And then this becomes a mailto
URL when you output it in a template etc;
<a href="mailto:{{ object.email }}">
{{ object.email }}
</a>
Upvotes: 1