Sunday, 18 October 2020

How to implement custom LanguageField in Django?

I am trying to create a custom LanguageField for my Language Django model to be able to work with django.conf.global_settings.LANGUAGES in my client-side code.

My goal is to have a_language.language.name return the name of a_language (i.e. "English") and Language.language.code return the code of a_language (i.e. "en").

languages/models.py:

from django.conf.global_settings import LANGUAGES

class Language(models.Model):

    language = LanguageField(languages=LANGUAGES)

    def __str__(self):
        return f"{self.language.name} ({self.language.code})"

languages/fields.py:

class LanguageField(models.Field):
    """
    I don't know what to do here but the logic would go something like 
    this...
    """
    def __init__(self, chosen_language, *args, **kwargs):
       self.name = chosen_language[1]
       self.code = chosen_language[0]
               
    

PS: django-countries implements something similar but with countries rather than languages. Maybe it could help.



from How to implement custom LanguageField in Django?

No comments:

Post a Comment