How to create Django Rest Framework translate mixin?

22 views Asked by At

I'm trying to write a django translate mixin for my project. I configured the settings.py file, created a model, view, serializer and mixin. when I run the application an error occurs: "TranslationFieldMixin.get_field_names() missing 2 required positional arguments: 'declared_fields' and 'info'". This error occurred after I added this code to my serializer:

def to_representation(self, instance):
        language = get_language()
        self.fields = self.get_field_names(language=language)  
        return super().to_representation(instance)

How can I solve this problem?

SETTINGS.PY

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'parler',
    'rest_framework',
    'store',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',

    'django.middleware.locale.LocaleMiddleware',

    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

]
LANGUAGE_CODE = 'en-us'

LOCALE_PATHS = [
    os.path.join(BASE_DIR, 'locale'),
]

LANGUAGES = [
    ('en', _('English')),
    ('es', _('Spanish')),
    ('fr', _('French')),
    ('ru', _('Russian')),
]

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

MODELS.PY

from django.utils.translation import gettext_lazy as _

class Article(models.Model):
    title = models.CharField(_('title'), max_length=100)
    content = models.TextField(_('content'))

    def __str__(self):
        return self.title

VIEWS.PY

class ArticleDetailAPIView(RetrieveUpdateDestroyAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

SERIALIZERS.PY

class ArticleSerializer(TranslationFieldMixin, serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ['id', 'title', 'content']

    def to_representation(self, instance):
        language = get_language()  

        self.fields = self.get_field_names(language=language) 

        return super().to_representation(instance)

UTILS.PY

class TranslationFieldMixin():
    def get_field_names(self, declared_fields, info, language=None, *args, **kwargs):

        field_names = super().get_field_names(declared_fields, info, *args, **kwargs)
        if language:
            translated_field_names = [
                str(_(field_name))
                for field_name in field_names
            ]
        else:
            translated_field_names = field_names

        return translated_field_names
0

There are 0 answers