In the first part of this tutorial series, we designed a translation app using the Django web framework. We saw how Django enabled dynamically writing to a web page. In this second part, we are going to continue from where we stopped by adding another feature to our Django app, a word counter.
π‘ Recommended: How I Created a Translation and Counter App using Django (1/2)
As we write inside the box, the textarea
HTML element, we want to know how many words have been written. If the words are translated into another language, we also want to get the number of words translated.
This is a nice feature you can implement in your project, perhaps, in a Django blog project, or Django social media website project, to get the length of words written.
I’m going to demonstrate how to do this using two programming languages, Python and JavaScript. This is probably the second time we are working with static files (JavaScript) in Django projects. The first time was when we designed a text-to-HTML converter app using Django.
Python and JavaScript are two programming languages with their pros and cons. Apart from improving your programming skills, the purpose of demonstrating this project using these two languages is for you to see how Python makes life easy for a beginner and how JavaScript adds dynamic behavior to a webpage. Learning these two languages is important as far as web development is concerned.
The full code is on my GitHub page. Please note that I included the two methods in the code. But for the sake of this tutorial, I assume that only one of the methods will be chosen by the user.
Using JavaScript
We start with the difficult one first. If you have successfully mastered JavaScript, you are to be commended. JavaScript, no doubt, is an easy language to learn but hard to master. And if you’re like me who is still learning the language, you will benefit from the numerous resources online.
As a continuation of the previous tutorial, create a folder in your current directory and name it static
. This folder will be used for static files such as CSS (not treated in this project) and JavaScript. Inside the folder, create another folder for our JavaScript file. Name the folder js
. Then, go to the settings.py
file and include the name of the static folder.
# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = 'static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] # add these # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
Next, go to the js
folder and create an empty file, script.js
using the touch
command. Then open your templates file, index.html
, and link the JavaScript file in two places. First at the top, just before the HTML syntaxes, write this:
{% load static %}
This loads all static files from the static folder. Second, after the closing body tag, write the script element that points to the location of the script.js file.
<script src="{% static 'js/script.js' %}></script>
The {% ... %}
block is a Django templating language. It is used to perform a for
loop, if
statement, linking to internal, and external webpages, and linking to static files.
It’s time to start coding. But since we are still in the index.html
file let’s use the opportunity to add a p
element after the two textarea
elements.
The first one will be like this:
<label for="django">Enter Text:</label> <br/> <textarea onChange="" id="translate" name="translate" placeholder="Enter your text here" rows="10" cols="70"></textarea> <p id="countText">Total words: 0</p> <!--add these -->
Then, the second will be like this:
<br> <textarea id="text" placeholder="Your text will appear here" rows='10' cols='70'>{{ translation }}</textarea> <p id="wordCount">Total words: 0</p> <!--add these -->
This is simply the number of words that will be shown. It’s set to 0. Using JavaScript, we are going to make that number change dynamically.
Take note of the id
property in all the textarea and p
elements. We are going to use them to manipulate the DOM. Now, go back to the script.js
file and add the following code to it.
const textArea = document.getElementById('translate'); textArea.addEventListener('input', () => { var textLn = textArea.value; document.getElementById('countText').innerHTML='Total words: '+getCount(textLn); }); const lan = document.getElementById('text'); lan.addEventListener('input', () => { let textLen = lan.value; document.getElementById('wordCount').innerHTML='Total words: '+getCount(textLen); });
We use the getElementById()
method to select the textarea
element. Then, we add an event listener to the DOM object using the addEventListener()
method.
We want something to be done when an action is taking place. What action are we talking about? Typing words inside the box (input). What do we want to be done? Counting the number of words typed. So, we attach an event handler that will be executed when the action or event occurs.
The event handler is an anonymous function or you call it a callback function.
Inside the function, we get the words written in the textarea
element using the .value
property. We then select another element, the p element, and change the innerHTML
. This overwrites the one we previously wrote in the templates file.
To get the length of words, we call another function with the value of the textarea
element passed as a parameter. The simple script is starting to look complicated. This is one of the reasons why JavaScript is difficult to master.
In JavaScript, a function can call a function which in turn calls another function, and so on. These functions can be deeply nested making it difficult for beginners to understand.
So, to keep things simple, we just pass the name of the next function and have it defined separately. This also makes our code readable.
getCount = str => { return str.split(' ').filter(num => { return num != '' }).length; }
The getCount()
function takes a string as a parameter and uses the string’s split
method to split the string. This becomes a JavaScript array. Next, we use the array filter
method to filter out empty spaces. This is done using an anonymous function. We are now left with an array of words. Then we simply count the number of words in the array using the array length
property.
The same thing was done for the other text area element. Run the local server.
Notice that as you type the number of words changes dynamically. But the second box is not displaying because there’s no input event going on. To initiate an input event, simply type a space bar inside the box, and you will see all the words counted.
Using Python
After demonstrating this using Python, you will no doubt appreciate the simplicity of the language, and why it is a good choice for beginners.
Open the views.py
file and add this function to it.
def wordCount(text): if text != '': word = len(text.split()) return word
If there is no space in the string, it splits it and returns the length. As simple as that. All that takes JavaScript several lines of code take Python just a few lines to accomplish.
Then update the view function and make it look like this:
def index(request): if request.method == 'POST': text = request.POST['translate'] lang = request.POST['language'] translator = Translator(to_lang=lang) translation = translator.translate(text) word1 = wordCount(text) word2 = wordCount(translation) context = { 'translation': translation, 'word1': word1, 'word2': word2 } return render(request,'index.html', context) return render(request, 'index.html')
Finally, go to the templates files and add p
elements under the second textarea element to display the results.
<textarea id="text" placeholder="Your text will appear here" rows='10' cols='70'>{{ translation }}</textarea> <p>Number of original text: {{ word1 }}</p> <p>Number of translated text: {{ word2 }}</p>
Run the local server.
Notice that it is only when the button is clicked, and the results shown that we can see the number of words typed. It wasn’t changing as we were typing the words.
Conclusion
In this tutorial, we created a word counter that counts the number of words written. We accomplished this using Python and JavaScript. Whichever language you prefer depends on what exactly you want.
- Do you want to write short code? Chose Python.
- Do you want to add dynamic behavior to a webpage? Choose JavaScript.
Nevertheless, the importance of learning the two languages, and working on projects such as these cannot be overemphasized.
π‘ Recommended: How I Built a Weather App Using Python Flask