How to create a translate project with Django

May 6, 2023


0
7 min read
2.26K

This article will create a translator app using Django, Django is a popular Python web framework. This app will allow users to input text in one language and receive a translation in another language. We will be using the translate python package to do the translation. If you want to learn Python and Django, then our courses are available, you can see them. Let us begin without wasting your time at all.

I think Django will be already installed in your system If not then you can install it like this:

pip install django

And Install the translate package:

pip install translate

Now let's create our project:

django-admin startproject translator

A project named translator will be created, you can do cd translator and go inside it.

cd translator

You have to create an app, you can give any name to the project and app, we have given it the name of app.

python manage.py startapp app

 Now you have to mention this app in your project setting in INSTALLED_APPS

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "app", # new
]

Create views that handle the translation. Now we need to create a view that will handle the translation. Open up app/views.py and add the following code:

from django.shortcuts import render
from translate import Translator

# Create your views here.


def home(request):
    if request.method == "POST":
        text = request.POST["translate"]
        to_lang = request.POST["tolanguage"]
        from_lang = request.POST["fromlanguage"]
        translator = Translator(to_lang=to_lang, from_lang=from_lang)
        translation = translator.translate(text)

        context = {
            "translation": translation,
        }
        return render(request, "home.html", context)
    return render(request, "home.html")

This code defines a view function called home() which is associated with the route for the homepage ("/") in a Django web application.

The function starts by checking the request method. If the request method is "POST", the function extracts data from the form submitted through the POST method. The text variable contains the text entered in the form, the to_lang variable contains the target language selected in the form and the from_lang variable contains the source language selected in the form.

A new instance of the Translator class from the translate module is then created, passing in the to_lang and from_lang variables as parameters. The translate() method of the Translator instance is then called with text as the argument to translate the text. The translated text is then stored in the translation variable.

Finally, a dictionary named context is created, which contains the translated text as a value associated with the key "translation". The home() function then renders the "home.html" template, passing in the context dictionary as a context variable.

If the request method is not "POST", the function simply renders the "home.html" template without any context variable.

We have to create the template mentioned in the views, and for that, we have to create a directory named templates inside our app, in that, we will write the code of the template.

home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Translate</title>
    <!-- Font Awesome -->
    <link
    href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"
    rel="stylesheet"
    />
    <!-- Google Fonts -->
    <link
    href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
    rel="stylesheet"
    />
    <!-- MDB -->
    <link
    href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.2.0/mdb.min.css"
    rel="stylesheet"
    />
    <style>
        .form-select{
            width: 120px;
        }
    </style>
</head>
<body>


    <!-- Navbar -->
<nav style="background-color: #474747;" class="navbar navbar-expand-lg navbar-dark">
    <!-- Container wrapper -->
    <div class="container-fluid my-2">
      <!-- Navbar brand -->
      <a class="navbar-brand" href="{% url 'home' %}">Django Translate App</a>
  
      <!-- Toggle button -->
      <button
        class="navbar-toggler"
        type="button"
        data-mdb-toggle="collapse"
        data-mdb-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent"
        aria-expanded="false"
        aria-label="Toggle navigation"
      >
        <i class="fas fa-bars"></i>
      </button>
  
      <!-- Collapsible wrapper -->
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <!-- Left links -->
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="{% url 'home' %}">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="{% url 'home' %}">Contact</a>
          </li>
        </ul>
        <!-- Left links -->
      </div>
      <!-- Collapsible wrapper -->
    </div>
    <!-- Container wrapper -->
  </nav>
  <!-- Navbar -->

        <!-- Textarea 8 rows height -->
<div class="row container-fluid mt-5">
    <div align="center" class="d-inline-block my-3">
        <form class="" method="post">
            {% csrf_token %}
        <p class=" d-inline">Choose Language </p>
        <select class="form-select d-inline me-4" required name="fromlanguage">
            <option value="fr">French</option>
            <option value="es">Spanish</option>
            <option value="de">German</option>
            <option value="it">Italian</option>
            <option value="en" selected>English</option>
            <option value="zh">Chinese</option>
            <option value="ig">Igbo</option>
            <option value="yo">Yoruba</option>
            <option value="hi">Hindi</option>
          </select>
        <span class="d-inline"><i class="fas fa-language fa-3x"></i></span>
        <select class="form-select d-inline ms-4" required name="tolanguage">
            <option value="fr">French</option>
            <option value="es">Spanish</option>
            <option value="de">German</option>
            <option value="it">Italian</option>
            <option value="en">English</option>
            <option value="zh">Chinese</option>
            <option value="ig">Igbo</option>
            <option value="yo">Yoruba</option>
            <option value="hi" selected>Hindi</option>    
          </select>
          <p class=" d-inline">Choose Language </p>
    </div>
    <div class="col-6">
        <div class="form-outline inline-block">
            <textarea onChange="" id="translate" name="translate" class="form-control" rows="8"></textarea>
            <label class="form-label" for="textAreaExample2">Enter Text</label>
        </div>
        <button id="btn" type="submit" class="btn btn-dark mt-3">
            Submit
          </button>
        </form>
        </div>
        <div class="col-6">
            <div class="form-outline inline-block">
                <textarea style="background-color: #ffffff;" id="formControlReadonly" class="form-control" rows="8" readonly>{% if translation %}{{translation}}{% endif %}</textarea>
                <label class="form-label" for="textAreaExample2">Translation</label>
            </div>
        </div> 
    </div>



 <!-- MDB -->
<script
type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.2.0/mdb.min.js"
></script>
</body>
</html>

This is an HTML code for a translation application using Django.

The code starts with the HTML boilerplate tags and includes several external libraries for Font Awesome, Google Fonts, and MDB UI Kit.

The navigation bar is defined using Bootstrap classes and includes a brand logo and collapsible menu with links to the home page and contact page.

The main content of the page includes a form for users to input text and select languages to translate from and to. The form includes two select elements for the source and target languages and a textarea element for the user to input the text to be translated. There is also a submit button for the user to submit the form.

To have a list of language codes you can add to your app visit the translate documentation https://translate-python.readthedocs.io/en/latest/index.html

Below the form, there are two columns for displaying the original and translated text. The original text is displayed in a read-only textarea element, and the translated text is displayed in another read-only textarea element which is updated dynamically using JavaScript.

Finally, the code includes a script tag for the MDB UI Kit library.

Now we will create URLs for these views For that, we have to create a file named urls.py inside our app.

from django.urls import path
from . import views

urlpatterns = [
    path("", views.home, name="home"),
]

We will include these URLs in our project URLs.

"""translator URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("app.urls")),
]

Run the server. Finally, we can run the server and test our app! In the terminal, navigate to the translator directory and run the following command:

python manage.py runserver

This will start the development server. Open up a web browser and go to http://127.0.0.1:8000/. You should see a form where you can enter text to translate and select the destination language. After submitting the form, the translated text should appear on the page.

 

In this article, we learned how to create a translator app using Django. We used the translate package to do the actual translation, and we created a simple web interface to allow users to enter text to translate. By following the steps outlined in this tutorial, you should now have a basic understanding of how to create web apps using Django.

django Project Project-Ideas Translate Appreciate you stopping by my post! 😊

Add a comment


Note: If you use these tags, write your text inside the HTML tag.
Login Required
Author's profile
Profile Image

Abdulla Fajal

Django Developer

With 'espere.in' under my care, I, Abdulla Fajal, graciously invite your insights and suggestions, as we endeavour to craft an exquisite online experience together.