rust-ssg/data/blog/posts/2012-01-05_custom-django-urlfield.rst
2023-10-14 14:10:23 -04:00

33 lines
1.5 KiB
ReStructuredText

Custom Django URLField
######################
:date: 2012-01-05 03:55
:author: tyrel
:category: Tech
:tags: python, django
:slug: 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.
.. code-block:: python
facebook_page = URLField(default_protocol="http", protocols=["https","ssh","spdy","mailto"])
The way I could improve this would be
.. code-block:: python
facebook_page = URLField(protocols=["https","https","ssh","spdy","mailto"])