How I Created a Translation and Counter App using Django

4.5/5 - (2 votes)

In this two-part tutorial series, we will learn how to create a translation app using Django. 🀠 As an extra feature, we are going to demonstrate two ways to create a word counter that counts the number of words written.

Translating text to a language one can understand is no longer a new development. As many businesses are done on an international level, it necessitates the need to communicate in a language the other party can understand.

Advancement in technology has removed the barrier to communication. With an app such as Google Translate, you can get the meaning of text written in another language.

As part of learning Django through building projects, we are going to implement such a feature.

What We Are Going to Learn

As earlier stated, this is a two-part series project tutorial. The first part focuses on building a translation app. In the second part, we are going to learn how to add another feature, a word counter. I’m going to show you how to go about building it using both JavaScript and Python.

By the end of this tutorial, you are not only going to learn how Django interacts with web pages, but you are also going to learn how to manipulate the DOM with JavaScript. Thus, even if you have little or no knowledge of HTML, CSS, and JavaScript, you can combine your knowledge of Python with my explanation to understand what we are doing.

Getting Started

Although this is a beginner Django project, I expect you to know the steps involved in setting up Django as I don’t have to be repeating myself whenever I’m writing a Django project tutorial. However, if this is your first time, check this article to learn how to install Django.

Your Django project should be created in the current folder using the name, translator. Then use app as the name of the Django app. After installation, go to the settings.py file and add the app name.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # custom app
    'app',

]

Creating the View Function

Next, go to the views.py file and add the following code to it.

from django.shortcuts import render
from translate import Translator


# Create your views here.

def index(request):
    if request.method == 'POST':
        text = request.POST['translate']
        lang = request.POST['language']
        translator = Translator(to_lang=lang)
        translation = translator.translate(text)
        
        context = {
            'translation': translation,
        }
        return render(request,'index.html', context)
    return render(request, 'index.html')

This is a very simple view function. We get the input from the HTML form provided it is a POST request. Then, we call on the Translator class of the translator module to translate the given text into the language selected. The Translator class has an argument, to_lang. This indicates the language you want your text to be translated.

We finally use the render function to display the translated text on the index.html web page. We can as well use the HttpResponse() function but it will not be displayed on the index.html web page.

But if the request method is not POST, we simply return the web page containing an empty form.

This part is as simple as it should be. But in future tutorials, we will be dealing with a more complicated view function.

The Templates

Next is the templates folder. Create the folder and add it to the settings.py file.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')], # add these
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Inside the folder, we create the index.html file.

<!DOCTYPE html>
<html>
  <head>
    <title>Django Translate</title>
  </head>
  <body>
    <h1>Django Translate App</h1>
    <form method="post">
      {% csrf_token %}

  <label for="django">Enter Text:</label>
  <br/>
  <textarea onChange="" id="translate" name="translate" placeholder="Enter your text here" rows="10" cols="70"></textarea>
  
      <br>
      <select required name="language">
        <option value="French">French</option>
        <option value="Spanish">Spanish</option>
        <option value="German">German</option>
        <option value="Italian">Italian</option>

      </select>
      <br>
      <br>
      <button id="btn" type="submit">Translate</button>
    </form>

  <br>

    <textarea id="text" placeholder="Your text will appear here" rows='10' cols='70'>{{ translation }}</textarea>
    
  </body>
    <script src="{% static 'js/script.js' %}"></script>
</html>

You can see the form element has the method property as POST. Without this, our view function will not work as expected. The csrf_token is a mandatory requirement for security. We use the select element to list the languages. You can add as many as you want.

Notice that the textarea and the select elements each has a name property, and if you check the view function, you will see that it has the same name as found in the HTML file. This is the way we retrieve data from the web page.

Finally, we register the URL of the app both in the project level and in the app level. For the project level, go to translate/urls.py file and add this:

from django.contrib import admin
from django.urls import path, include

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

For the app level create a app/urls.py file and add this:

from django.urls import path
from .views import index

urlpatterns = [
    path('', index, name='home'),
]

Check the article I mentioned to see a brief explanation of the above code. That’s it. We are good to go. Fire up the local server to test what we have done.

Notice how we make the translated text appear inside the box. We accomplished this using Django templating language. Remember the context variable passed to the render() function? It is a dictionary object, the name of the key being what we passed to the textarea element. Thus, we are telling Django to display the value of the key to the web page.

And what is the value? The translated text! That is how Django dynamically writes to a web page. Feel free to play with any language of your choice provided the language is included in the translate library.

Conclusion

This is how we come to the end of the first part of this tutorial series. The full code for the project series can be found here. In the second part, we will learn two ways we can count the number of words written in the textarea element:

πŸ’‘ Recommended: How I Created a Translation and Counter App using Django (2/2)