[Answered ]-Django: set language

1👍

Typically you construct a Language model, for example:

class Language(models.Model):
    code2 = models.CharField(max_length=2, primary_key=True)
    name = models.CharField(max_length=128, unique=True)

    def __str__(self):
        return self.name

we can populate that, for example with ('en', 'English') and ('fr', 'French') and ('ja', 'Japanese').

Next we add a ManyToManyField [Django-doc] between the Profile and the Language:

class Profile(models.Model):
    languages = models.ManyToManyField(Language, related_name='speakers')

    def __str__(self):
        return f'{self.user.get_full_name()}'

In the admin, we can make selecting languages more convenient with:

from django.contrib import admin


class ProfileAdmin(admin.ModelAdmin):
    # …
    autocomplete_fields = ('languages',)

Leave a comment