question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

I wrote a Mixin for a DRF-API-View to dynamically support django-modeltranslation

See original GitHub issue

I wrote a Mixin for the django-restframework API View to automatically deliver translations. Here is an example for German and English activated:

class AchievementSerializer(TranslatableSerializerMixin, serializers.ModelSerializer):
    class Meta:
        model = Achievement
        fields = ('slug', 'title',)

When you now make a GET request to it, you will get this as a return:

{
	"count": 6,
	"current_page": 1,
	"results": [{
		"slug": "campaign",
		"title": "Kampagne",
		"title_de": "Kampagne",
		"title_en": "Campaign"
	}, {
		"slug": "profile",
		"title": "Profil",
		"title_de": "Profil",
		"title_en": "Profile"
	}, {
		"slug": "promote-project",
		"title": "Projekt bekannt machen",
		"title_de": "Projekt bekannt machen",
		"title_en": "Promote Project"
	}, {
		"slug": "company",
		"title": "Unternehmen",
		"title_de": "Unternehmen",
		"title_en": "Company"
	}, {
		"slug": "organization",
		"title": "Organisation",
		"title_de": "Organisation",
		"title_en": "Organization"
	}, {
		"slug": "project",
		"title": "Projekt",
		"title_de": "Projekt",
		"title_en": "Project"
	}],
	"links": {
		"previous": null,
		"next": null
	}
}

You can also POST to it like normal.

Issue Analytics

  • State:open
  • Created 6 years ago
  • Reactions:6
  • Comments:5

github_iconTop GitHub Comments

5reactions
emorozovcommented, May 28, 2017

@iekadou How we can see the code of your mixin? Why didn’t you create a pull request?

1reaction
ilikerobotscommented, Jan 16, 2019

Here’s a simple implementation of the above (mixin renamed). By default, it will provide all translations of the serializer fields. However, if the language get parameter is provided to the request as a comma delimited string, then only those specified translations will be returned.

from django.conf import settings
from modeltranslation.manager import get_translatable_fields_for_model
from rest_framework import serializers


class TranslatedModelSerializerMixin(serializers.ModelSerializer):
    def get_field_names(self, declared_fields, info):
        fields = super().get_field_names(declared_fields, info)
        trans_fields = get_translatable_fields_for_model(self.Meta.model)
        all_fields = []

        requested_langs = []
        if 'request' in self.context:
            lang_param = self.context['request'].query_params.get('lang', None)
            requested_langs = lang_param.split(',') if lang_param else []

        for f in fields:
            if f not in trans_fields:
                all_fields.append(f)
            else:
                for l in settings.LANGUAGES:
                    if not requested_langs or l[0] in requested_langs:
                        all_fields.append("{}_{}".format(f, l[0]))

        return all_fields
Read more comments on GitHub >

github_iconTop Results From Across the Web

django - Set created by modified by dynamically with mixin
Just use existing functionality https://docs.djangoproject.com/en/1.11/topics/db/models/#abstract-related-name class Trackable(models.
Read more >
Using mixins with class-based views - Django documentation
Two central mixins are provided that help in providing a consistent interface to working with templates in class-based views. TemplateResponseMixin.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found