tfranzel / drf-spectacular

Sane and flexible OpenAPI 3 schema generation for Django REST framework.
https://drf-spectacular.readthedocs.io
BSD 3-Clause "New" or "Revised" License
2.37k stars 262 forks source link

Different enum names for different locales in the final schema #1198

Open WhoisUnknown opened 7 months ago

WhoisUnknown commented 7 months ago

Describe the bug When using models.TextChoices and gettext_lazy get different names for the enum in the resulting schema and swagger UI

To Reproduce

view.py

from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from rest_framework.decorators import api_view
from django.db import models
from drf_spectacular.utils import (
    extend_schema,
    inline_serializer,
)

class BuyCommonErrorCode(models.TextChoices):
    SOME_ERROR = "some_error", _("Description about error")

@extend_schema(
    summary="Test url",
    request=inline_serializer(
        "SomeSerializer",
        fields={
            "custom_error": serializers.ChoiceField(
                choices=BuyCommonErrorCode.choices,
                required=False,
            ),
        },
    ),
)
@api_view(["POST"])
def test_url(request):
    return Response(None)

settings.py

SPECTACULAR_SETTINGS = {
    "TITLE": "Core API",
    "VERSION": "1.0.0",
    "SERVE_INCLUDE_SCHEMA": False,
    "COMPONENT_SPLIT_REQUEST": True,
    "COMPONENT_NO_READ_ONLY_REQUIRED": False,
    "ENUM_ADD_EXPLICIT_BLANK_NULL_CHOICE": False,
    "COMPONENT_SPLIT_PATCH": True,
    "SCHEMA_PATH_PREFIX": "/api/",
    "PARSER_WHITELIST": ["rest_framework.parsers.JSONParser"],
    "ENUM_NAME_OVERRIDES": {
        "BuyCommonErrorCode": "main.views.BuyCommonErrorCode",
    },
}
  1. Translate string in .po file
  2. python manage.py makemessages -l es
  3. django-admin compilemessages -l es
  4. Go to swagger UI
  5. Set query in url. I.g. http://127.0.0.1:7050/docs/full-api/?lang=en and http://127.0.0.1:7050/docs/full-api/?lang=es
  6. Compare enum in Scheme. Enums names is different

Spain swagger scheme

image

English swagger scheme image

Expected behavior Same name for Enum for each locale

tfranzel commented 7 months ago

yes, that looks like a bug. The enum hash identifier is calculated with the default language. When you request another language, the hash is different, due to different strings and so the matching fails.

WhoisUnknown commented 6 months ago

I tested the master branch. Everything is fine! Thank you so much!