Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow_blank not properly reflected for more strictly typed string fields #909

Open
StopMotionCuber opened this issue Jan 4, 2023 · 1 comment

Comments

@StopMotionCuber
Copy link
Contributor

StopMotionCuber commented Jan 4, 2023

Describe the bug
I'm having an API, where the field is regex based (URLField in this case), and that field can be blank. However, the schema that is generated does not take that into account and does not document the possibility for blank values.

Opposed to a CharField, a blank value is not valid per strict value (in this case the URL), so additional magic is required to make that possible.

To Reproduce

class Service(models.Model):
    service_hyperlink = models.URLField(help_text="Hyperlink for the service. Can be used to reference a service.",
                                        blank=True)

class ServiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Service
        fields = ['service_hyperlink']
        extra_kwargs = {
            "service_hyperlink": {"allow_blank": True}
        }

Expected behavior
A schema is generated where a blank value is possible. Something along the lines of the following, using oneOf:

service_hyperlink:
  oneOf:
  - type: string
    format: uri
  - enum:
    - ""
    type: string

Additional reference
With a custom field, this workaround should already be possible by putting the according oneOf annotation to that field. I think that having this fixed in the library would be the nicer solution though.

@StopMotionCuber
Copy link
Contributor Author

Update: The workaround I proposed does not really work greatly with drf-spectacular. Trying to use a custom field as follows:

@extend_schema_field({"oneOf": [build_basic_type(OpenApiTypes.URI), {"enum": [""], "type": "string"}]})
class BlankUrlField(URLField):
    pass

This generates the same documentation as when using an URLField.
However, using

@extend_schema_field({"oneOf": [build_basic_type(OpenApiTypes.URI), {"enum": [""], "type": "string"}]})
class BlankUrlField(Field):
    pass

the documentation is generated as expected (though the behavior is obviously not the way that I want). Probably something about precedence, that custom annotations are not evaluated when inbuilt fields are detected

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant