blog/content/2012/01/2012-01-05_custom-django-urlfield.rst
2022-10-16 23:34:35 -04:00

26 lines
1.5 KiB
ReStructuredText

Custom Django URLField
######################
:date: 2012-01-05 03:55
:author: tyrel
:category: Tech
:tags: python, django
:slug: 2012-01-05-custom-django-urlfield
:status: published
For work I had to write a custom url model field. This model field when setting up accepts a default protocol, and a list of other protocols.
| When checking the protocol, the url is split by “://”. If the split has one or two parts, then the url is validly formed.
| In the event of a single element split, there is no protocol specified. When there is no protocol, the url is prepended with the default protocol specified. If there is a protocol, it is checked to make sure it exists in a union of the default protocol and other protocols. If it is not, a ValidationError is raised letting the user know that the protocol is not accepted.
This can all be found at On my github [deadlink].
| I have a couple ways I could have done this better and probably will. Improvements would be just one parameter called parameters in which it is checked if there is at least one element. Passing this, when there is no protocol specified, the first element is the default one.
| This would be a little cleaner.
| this example would allow for http, https, ssh, spdy and mailto, anything else would error out.
| ``facebook_page = URLField(default_protocol="http",``
| ``protocols=["https","ssh","spdy","mailto"])``
| The way I could improve this would be
| ``facebook_page = URLField(protocols=["https","https","ssh","spdy","mailto"])``