[Fixed]-Django URLField with custom scheme

13๐Ÿ‘

โœ…

As @IainDillingham mentioned in the comments, this is a bug in Django: overriding the default_validator of a subclassed ModelField does not necessarily override the default_validator of the FormField to which that base class is associated.

For your example, django.db.models.URLField, we can see its associated form field[0] is django.forms.fields.URLField[1]. So the workaround here is to also override def formfield(...) for your customized SSHURLField, to reference a custom django.forms.fields.URLField subclass with the same validator, like so:

from django.core import validators
from django.db import models
from django.forms.fields import URLField as FormURLField

class SSHURLFormField(FormURLField):
    default_validators = [validators.URLValidator(schemes=['ssh'])]

class SSHURLField(models.URLField):  
    '''URL field that accepts URLs that start with ssh:// only.'''  
    default_validators = [validators.URLValidator(schemes=['ssh'])]  

    def formfield(self, **kwargs):
        return super(SSHURLField, self).formfield(**{
            'form_class': SSHURLFormField,
        })

[0] https://github.com/django/django/blob/e17088a108e604cad23b000a83189fdd02a8a2f9/django/db/models/fields/init.py#L2275,L2293
[1] https://github.com/django/django/blob/e17088a108e604cad23b000a83189fdd02a8a2f9/django/forms/fields.py#L650

๐Ÿ‘คJoseph

Leave a comment