[Django]-How to serialize a CountryField from django-countries?

3👍

For the serializer, you import the CountryField of the django_countries.serializer_fields module, so:

from django_countries.serializer_fields import CountryField

class CustomRegisterSerializer(RegisterSerializer):
    # …
    country = CountryField()
    # …

If you instead want to work with the Mixin (which will use such CountryField serializer field), you should specify the CountryFieldMixin before the RegisterSerializer, otherwise it will not override the .build_standard_field(…) method.

You thus inherit with:

class CustomRegisterSerializer(CountryFieldMixin, RegisterSerializer):
    # …

In that case you should not specify the country serializer field manually, since that will render the mixin ineffective.

Leave a comment