How to add localization to Django REST Framework

Pasindu Prabhashitha
Ascentic Technology
9 min readAug 29, 2022
Django

In this article, I’m going to give you a guide on how you can localize your Django Rest API using I18N and Django Rest Framework.

Before starting the tutorial I’ll give you a brief introduction to Django and Django REST Framework.

First things first What exactly Django is?

Django is a free and open-source Python web framework that follows the MVT(Model View Template) pattern and you can build fast, secure, and scalable web applications using this framework. It’s a batteries-included framework and there you can reduce the development time drastically.

What is the Django Rest framework?

Django Rest framework is the rest implementation of the Django web framework and using this, you can create a REST API using a low amount of code with Django.

That was the intro. Now let’s start.

Setting up the virtual environment

The first thing you have to do is initialize a new Django Project. For that, you should have installed Python on your device. Usually, when I develop Django Applications, I do that inside a virtual environment. When you use a virtual environment, you can install the pip packages inside that virtual environment. Otherwise, these packages will install globally in your pc.

To set up a virtual environment use Pipenv.

You can install it using the following command. Please make sure that you have installed Python before running these commands.

pip install — user pipenv

After that go to a new directory where you need to initialize the application and create a new folder called .venv inside it. When you create this folder virtual environment automatically detects this folder and installs all the packages inside this folder.

Installing Django

Now we can install Django Inside our virtual environment. For that run

pipenv install Django

Creating a new Django Project

Now we have to create a new Django project. We can do it by running the following command.

django-admin startproject localization

With this command, it will create a new Django Project which has name localization inside a folder called localization. Since there are two folders named localization, I will take the inner folder named localization to the root directory. This way we can have a better folder structure. Now your folder structure looks like the following.

.venv
localization
- __init__.py
- asgi.py
- settings.py
- urls.py
- wsgi.py
manage.py
Pipfile

After that, you can turn on the Django project by running

py manage.py runserver

Creating a new app

Okay, Now we have done the initialization of the project. Now I’ll create another app to demonstrate localization. Wait? But what is an app inside Django application?

An app is a web application that does something — e.g. a blog system, a database of public records, or a small poll app

To learn about more go to Django Docs https://docs.djangoproject.com/en/4.0/intro/tutorial01/

To create such an app you need to type the following command. I assume that we are creating a blog app.

python manage.py startapp blog

After you run this command, you can see our new Django App has been created inside our directory

Installing Django REST Framework

Now we need to install Django Rest Framework to build our API Endpoint. You can install Django Rest Framework through the following commands from the python package index.

pipenv install djangorestframeworkpipenv install markdownpipenv install django-filter 

We should install markdown and Django filter along with Django Rest Framework to work the Django REST API correctly.

Now we have successfully installed it. Now we need to get it working inside our application. For that, you have to do some configurations.

First of all, go to the settings file inside the localization folder and scroll down to the installed apps section. After that place rest_framework inside the list as below screenshot.

Creating First API Endpoint

Now I’m going to create my first API endpoint inside our project. To create it go to the views file inside the blog app, delete everything and paste the following code.

from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view()
def hello_world(request):
message = "This is my first Django API"
return Response({"message": message})

This is a function-based API View that returns the message “This is my first Django API” as the response.

Registering the Endpoint

After that, we need to register this view inside our urls.py file. This way Django App will be able to access this function. To do that go to urls.py inside the blog app and paste the following code there. This will import our hello world function to the urls.py file and register it inside the app.

from .views import hello_world
from django.urls import path
urlpatterns = [
path('message', hello_world),
]

Now we have registered it inside the blog app but we need to register the blog app’s URLs inside the project. For that, you need to go to the urls.py inside the localization folder and you have to add the following code there.

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/blog/', include('blog.urls')),
]

That’s it. Now when you visit this URL http://localhost:8000/api/blog/message you should see our message inside the browsable API.

Setting up translations

The very first thing you have to do is add the following code to the end of the settings file and make sure to import os at the top of the file. The gettext function will define our translation strings and for the convention, we add a _ alias to it. The settings file is located inside the localization folder.

from django.utils.translation import gettext as _
import os

After that at the bottom, we should add the list of languages in order to make translations work. You can do it like by the following snippet.

# Available Languages
LANGUAGES = [
('sv', _('Swedish')),
]
# Locales available path
LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale/')
]

The LANGUAGES list will define what are the other languages inside this project and the LOCALE_PATHS define from where Django can find the translation strings. After that create a folder code locale at the root of the project. Now the folder structure should be looks like the following.

.venv
blog
locale
localization
- __init__.py
- asgi.py
- settings.py
- urls.py
- wsgi.py
manage.py
Pipfile

Mark translation strings

After that go to that views.py we previously created and import the gettext function from Django.utils like following

from django.utils.translation import gettext as _

The complete code inside that file should be like the below snippet.

from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.utils.translation import gettext as _
@api_view()
def hello_world(request):
message = "This is my first Django API"
return Response({"message": message})

After that, you can pass the sentence as a parameter to the gettext function. After we add it when we run the following command Django will scan the project and detects the words that have wrapped with the gettext function. In that way, it identifies the words we need to translate and it will create a translations file for that words. For one language there will be one translation file inside that locale folder we created.

This is the code snippet after we wrap our message variable with the gettext function.

from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.utils.translation import gettext as _
@api_view()
def hello_world(request):
message = _("This is my first Django API")
return Response({"message": message})

Since we use an alias called _ we can wrap the message with that alias instead of typing the entire gettext word.

Generating the translation file

After that generating the translation file is very easy. Below is the command

django-admin makemessages -l sv

We should specify the locale that we need to make a translation file. In my case it’s Swedish since I have added it to the settings file as sv I added it here as sv. At this point, if you encounter an error most probably that’s because you haven’t installed the GNU gettext tool. So follow the below link and install it. It’s pretty straightforward.

If the above command is successful the translation file should be created. If you carefully go through the translation file you can see the strings we marked for translation have been added to the translation file. Check the below pictures.

Generated translation file

Content inside the translation file

Now we can add the Equivalent Swedish translation string like below.

Compiling translation strings

After that, we need to compile this translation file in order to make this work. For that, you need to run the following command.

py manage.py compilemessages

After that, another file will be created and inside that, the compiled version of the translation strings exists.

Compiled translation file

Add another language

Now you can add another language to your app by following the above steps. In my case, I added Spanish. First I added it to the language list in the settings file and after that, I added LANUAGE_CODE=”es” in this way Django identifies the default language we want to use. So here the default language will be Spanish.

Adding spanish language to Django Rest Framework

And then run the make messages command.

django-admin makemessages -l es

This time since we use es it will create a Spanish translation file. After that add an equivalent Spanish string.

Spanish translation file

Then compile the translation file as before.

py manage.py compilemessages

That was the final step. We have successfully set up the translations inside our rest framework.

Testing the application

Now I’m going to test this endpoint with Postman. Postman is an API testing tool that we can use to test our APIs.

First, start the Django project as usual by running

py manage.py runserver

Now go to the postman and create a get request like this. You don’t need to use Postman. Just test it in your own way. Now since our default language is set to Spanish it will send the response in Spanish.

Django Rest framework localization testing

But now if you need to change the language to Swedish you need to pass Accept-Language as sv in a header. Check the example below. But we have to add a middleware to the Django middleware setting in order to let the Django REST Framework identify our language header. To do that go to the setting.py and find the list of middleware and add the following middleware to it as follows.

'django.middleware.locale.LocaleMiddleware'

And that’s it now when you send a request by Adding a Accept-Lanuage header as sv it will send the response in the Swedish language. Check the below picture.

After add localization middleware to the Django REST Framework

That’s it for this article. If you need the code I followed as a reference you can get it by visiting the following repository.

https://github.com/PasinduPrabhashitha/Django-Rest-Framework-Localization

Thanks for reading. Hope you got some knowledge regarding the process. If you have got any questions drop a comment below.

--

--