Building a Translation app Using Django

In this post, we'll build a simple translation app that translates a text to different languages.
So if you'd like to have an app like google translate, you are in the right place.

Before getting started, let's see what we'll build:

Building a Translation app using Django

And now, let's get started.

Technologies

  • Django==3.1.4
  • googletrans==3.1.0a0

Setting up Django Project

If you already have set up Django project, you can move to the next part.

If not, you need to follow these steps:


mkdir DJangoTextTranslation



cd DJangoTextTranslation

Create a Virtual Environments.


virtualenv -p /usr/bin/python3 env

Activate it.


source env/bin/activate

Install Django.


pip install django

Start our project.


django-admin startproject DJangoTextTranslation

Start the app.


cd DJangoTextTranslation


django-admin startapp core

in DjangoBs/settings.py add app to INSTALLED_APPS


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    #Apps
    'core',
]

Allow all hosts.


ALLOWED_HOSTS = ['*']

Set TEMPLATES directory path.


'DIRS': [os.path.join(BASE_DIR, 'TEMPLATES')],

Create TEMPLATES folder inside our project.


mkdir TEMPLATES

Migrate.


python3 manage.py migrate

Run server.


python3 manage.py runserver


System check identified no issues (0 silenced).
December 28, 2020 - 22:47:26
Django version 3.1.4, using settings 'Backend.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Great!

Project structure:


├── core
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── __pycache__
│   ├── tests.py
│   └── views.py
├── db.sqlite3
├── DJangoTextTranslation
│   ├── asgi.py
│   ├── __init__.py
│   ├── __pycache__
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
└── TEMPLATES




Installing the googletrans library

To translate text, we'll use the googletrans library, which is free and unlimited.

Installing:


pip install googletrans

How to use googletrans

Before writing the Django translation app, we need to know how to use the googletrans library.

Run python:


(env) py@py:~/*/DJangoTextTranslation$ python3

Importing the module:


>>> from googletrans import Translator

By default, the googletrans library translates to English.

Let's try to translate a french sentence:


>>> translator = Translator()
>>> tr = translator.translate('bonjour je suis albert')
>>> tr.text
"hello i'm albert"

To choose the language, we need to assign language code to the dest argument.

Translating to Spanish:


>>> tr = translator.translate('bonjour je suis albert', dest='es')
>>> tr.text
'hola soy albert'

All languages' codes:


LANGUAGES = {
    'af': 'afrikaans',
    'sq': 'albanian',
    'am': 'amharic',
    'ar': 'arabic',
    'hy': 'armenian',
    'az': 'azerbaijani',
    'eu': 'basque',
    'be': 'belarusian',
    'bn': 'bengali',
    'bs': 'bosnian',
    'bg': 'bulgarian',
    'ca': 'catalan',
    'ceb': 'cebuano',
    'ny': 'chichewa',
    'zh-cn': 'chinese (simplified)',
    'zh-tw': 'chinese (traditional)',
    'co': 'corsican',
    'hr': 'croatian',
    'cs': 'czech',
    'da': 'danish',
    'nl': 'dutch',
    'en': 'english',
    'eo': 'esperanto',
    'et': 'estonian',
    'tl': 'filipino',
    'fi': 'finnish',
    'fr': 'french',
    'fy': 'frisian',
    'gl': 'galician',
    'ka': 'georgian',
    'de': 'german',
    'el': 'greek',
    'gu': 'gujarati',
    'ht': 'haitian creole',
    'ha': 'hausa',
    'haw': 'hawaiian',
    'iw': 'hebrew',
    'he': 'hebrew',
    'hi': 'hindi',
    'hmn': 'hmong',
    'hu': 'hungarian',
    'is': 'icelandic',
    'ig': 'igbo',
    'id': 'indonesian',
    'ga': 'irish',
    'it': 'italian',
    'ja': 'japanese',
    'jw': 'javanese',
    'kn': 'kannada',
    'kk': 'kazakh',
    'km': 'khmer',
    'ko': 'korean',
    'ku': 'kurdish (kurmanji)',
    'ky': 'kyrgyz',
    'lo': 'lao',
    'la': 'latin',
    'lv': 'latvian',
    'lt': 'lithuanian',
    'lb': 'luxembourgish',
    'mk': 'macedonian',
    'mg': 'malagasy',
    'ms': 'malay',
    'ml': 'malayalam',
    'mt': 'maltese',
    'mi': 'maori',
    'mr': 'marathi',
    'mn': 'mongolian',
    'my': 'myanmar (burmese)',
    'ne': 'nepali',
    'no': 'norwegian',
    'or': 'odia',
    'ps': 'pashto',
    'fa': 'persian',
    'pl': 'polish',
    'pt': 'portuguese',
    'pa': 'punjabi',
    'ro': 'romanian',
    'ru': 'russian',
    'sm': 'samoan',
    'gd': 'scots gaelic',
    'sr': 'serbian',
    'st': 'sesotho',
    'sn': 'shona',
    'sd': 'sindhi',
    'si': 'sinhala',
    'sk': 'slovak',
    'sl': 'slovenian',
    'so': 'somali',
    'es': 'spanish',
    'su': 'sundanese',
    'sw': 'swahili',
    'sv': 'swedish',
    'tg': 'tajik',
    'ta': 'tamil',
    'te': 'telugu',
    'th': 'thai',
    'tr': 'turkish',
    'uk': 'ukrainian',
    'ur': 'urdu',
    'ug': 'uyghur',
    'uz': 'uzbek',
    'vi': 'vietnamese',
    'cy': 'welsh',
    'xh': 'xhosa',
    'yi': 'yiddish',
    'yo': 'yoruba',
    'zu': 'zulu',
}



For more Features, visit the googletrans documentation.

Django Translation app

After learning how to use the googletrans library, it's time to write a simple Django Translation app.

in core/views.py


from django.shortcuts import render

from googletrans import Translator



def translate_app(request):
    if request.method == "POST":
        lang = request.POST.get("lang", None)
        txt = request.POST.get("txt", None)

        translator = Translator()
        tr = translator.translate(txt, dest=lang)

        return render(request, 'translate.html', {"result":tr.text})

    return render(request, 'translate.html')

Let me explain:

After submitting the form:

1. get text and language's code from the form's inputs.
2. Translate the text.
3. Return the result.

Add a path for our view:

DJangoTextTranslation/urls.py:


path('translate/', translate_app, name='trans')

Create translate.html in the TEMPLATES folder and add the following lines:


<!DOCTYPE html>
<html>
   <head>
      <title>Translate app</title>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
   </head>
   <style>
      p {font-size: 20px} 
      h1{text-align: center;}
   </style>
   <body>
      <div class="container">
         <h1 class="mt-5 mb-5">Translate App</h1>
         <form method="POST" action="{% url 'trans' %}">
            {% csrf_token %}
            <div class="form-row mt-4">
               <div class="col">
                  <textarea type="text" name="txt" class="form-control" placeholder="Enter Your Text" rows="5" required="required"></textarea>
               </div>
               <div class="col">
                  <select id="inputState" class="form-control" name="lang">
                     <option selected value="en">English</option>
                     <option value="ar">Arabic</option>
                     <option value="es">Spanish</option>
                     <option value="fr">Frensh</option>
                     <option value="de">German</option>
                     <option value="zh-cn">Chinese</option>
                  </select>
               </div>
            </div>
            <button type="submit" class="btn btn-primary mt-2">Translate</button>
         </form>
         <p class="mt-4">{{result}}</p>
      </div>
   </body>
</html>

Go to http://127.0.0.1:8000/translate :

Building a Translation app using Django

Project on GitHub

The project is available on Github so, You can download it by clicking the link below:
Django Translation App

Finally, I hope this tutorial helps.

See you later!

English today is not an art to be mastered it's just a tool to use to get a result