How to use Google Translator in Django?

Published On: 09/09/2022 | Category: Django


Hi Dev,

This tutorial is focused on how to use google translator in django. I’m going to show you about translator app in django. this example will help you text translation with google translate api in django. step by step explain django translator example.

In Django google translate library used for multi language website without entering manually the translation of your website words. django also provide multi language website using localization but you need to add every work on a configuration file. so using google translate you don't have to do anything.

In this example 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.

Here i explained simply step by step example of how to use google translator in django.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2: Create a App

Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python3 manage.py startapp core
Step 3: Update setting.py

Then update INSTALLED_APPS within our settings.py file to notify Django about the app.

settings.py

....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]
Step 4: Installing the googletrans library

In this section first of all we need to install googletrans library through below following command:

pip install googletrans
Step 5: Creating the Views

In this step, we need to configure views. The translate_app page will just be a template. function is basically get the language value form you choose the dropdown open the core/views.py file and add:

core/views.py
from django.shortcuts import render
from googletrans import Translator

# Create View
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')
Step 6: Creating the Templates

Next, then with your text editor create new templates files: core/templates/translate.html file and the add:

core/templates/translate.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tuts-Station.com</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <style type="text/css">
        body{
            background-color: #f7fcff;
        }
    </style>
</head>
<body>
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h4>Django Google Translate Example Tutorial - <span class="text-primary">Tuts-Station.com</span></h4>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="{% url 'trans' %}">
                            {% csrf_token %}
                            <div class="row">
                               <div class="col-md-12">
                                  <textarea type="text" name="txt" class="form-control" placeholder="Enter Your Text" rows="3" required="required"></textarea>
                               </div>
                            </div>
                            <div class="row mt-2">
                                <div class="col-md-12">
                                    <select id="inputState" class="form-control" name="lang">
                                        <option selected value="en">English</option>
                                        <option value="es">Spanish</option>
                                        <option value="fr">French</option>
                                        <option value="hi">Hindi</option>
                                    </select>
                                </div>
                            </div>
                            <div class="row mt-2">
                                <div class="col-md-12 text-center">
                                    <button type="submit" class="btn btn-primary mt-2 btn-block">Translate</button>
                                </div>
                            </div>
                        </form>
                        <p class="mt-4">{{result}}</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
Step 7: Creating URLs

In this section, we need a urls.py file within the core app however Django doesn't create one for us with the startapp command. Create core/urls.py with your text editor and paste below code.

core/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('translate/', views.translate_app, name='trans')
]

Next, we require to add a URL path for our example app which can be done by importing include and setting a path for it.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
]
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/translate address with a web browser.

I hope it will help you....

Happy Coding!

Note: So, googletrans suppored to this all languages' codes look like this:

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',
}