The Wayback Machine - https://web.archive.org/web/20240930190700/https://www.geeksforgeeks.org/create-word-counter-app-using-django/
Open In App

Create Word Counter app using Django

Last Updated : 25 May, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we are going to make a simple tool that counts a number of words in text using Django. Before diving into this topic you need to have some basic knowledge of Django.

Refer to the below article to know about basics of Django.

Now moving forward to make our wordcounter, first, we need to create a function where we can write the logic for counting words. 

views.py

Python3




from django.shortcuts import render
  
  
# defining function for wordcounter
def counter(request):
    # checking if method is POST or not
    if request.method == 'POST':
  
        # taking text input
        text = request.POST['texttocount']
  
        # checking weather text is empty
        # or not
        if text != '':
  
            # splitting the text and taking length
            # of that
            word = len(text.split())
  
            # defining boolean so that we can keep
            # track of process later
            i = True
  
            # returning HTML page with data, if calculated
            # successfully
            return render(request, 'counter.html',
                          {'word': word, 'text': text, 'i': i, 'on': 'active'})
  
        else:
            # returning HTML page without data, if any
            # error occurs
            return render(request, 'counter.html', {'on': 'active'})
  
    else:
        # returning HTML page if request.method is not POST
        return render(request, 'counter.html', {'on': 'active'})


 Explanation:

First, we created a counter function that will receive text input from the frontend. After that, it will check if the text is empty or not. Then it will split the words from the text and measure the length of them. Also, store that length into a variable named “word”. We have also created one Boolean which will be used to keep track of the process later. If this process gets completed successfully then it will return an HTML page with data stored in word & text. And if the process can’t be completed successfully then it will return the same HTML page without any data.

After creating the function, we need to define a URL for that. We will be using http://localhost:8000/counter here. For that open your urls.py folder and write the following code.

Python3




from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
  
urlpatterns = [
    path('counter',views.counter, name='counter'),
]


  After this, we need to create an HTML page for that. Here you can use your Designing skills and prepare your own design and name it counter.html.  Over here we will show the logic which you can frontend. 

First of all, we will check that Boolean is true or false to know the process completed successfully or not. If that is true then we can move forward. Later on, we will use the word variable to print output with the help of Jinja format. Then we will create form to take data from user which will be sent inside our counter function. Since we are using the POST method to handle requests, we have to give  {% csrf_token %} to that.

counter.HTML

HTML




{% if i %}
<div class="mb-2" style="border-style: groove;border-radius: 10px;">
  <div class="card-header">
    <p class="m-0" style="font-size: 20px;">{{word}} Word's in that text</p>
  
  
  </div>
</div>
{% endif %}
  
<div class="col-12 pb-3" style="background-color:  #c2d6d6; border: 2px; border-style: groove; border-radius: 10px;">
  <form action="counter" method="POST"> {% csrf_token %}
    <div class="form-group">
      <label for="text1">Paste you're text</label>
      <textarea class="form-control" placeholder="Paste you're text here to count word and character" 
                name="texttocount" id="text1" rows="8" style="background-color: #f0f5f5;">{{text}}</textarea>
    </div>
      
    <!-- ads section start-->
    <div class="text-center">
      ads
    </div>
      
    <!-- ads section end -->
    <div class="form-group text-center">
      <button type="submit" class="btn btn-primary w-25" >Run Counter</button>
    </div>
  </form>
</div>


Output:

TemplateDoesNotExist at /counter



Previous Article
Next Article

Similar Reads

Python - Counter.items(), Counter.keys() and Counter.values()
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python’s general-purpose built-ins like dictionaries, lists and tuples. Counter is a sub-class that is used to count hashable objects. It imp
3 min read
Create a Counter App Using React, Tailwind and Django Framework
This article will guide you in creating a Counter using React and Tailwind with the Django Framework. We’ll explore the integration of Django, React, and Tailwind, and go through the step-by-step process of implementing the Counter in Python using the Django Framework. What is Counter App?The Counter app is a straightforward tool designed for easy
6 min read
Create Social Media Feed App using Django
In this tutorial, we'll build a basic social media feed using Django, the Python web framework. A social media feed is a core component of platforms like Facebook, Instagram, and Twitter, allowing users to view and interact with posts, comments, and likes in real-time. By the end of this tutorial, you'll have a fully functional social media feed wh
14 min read
Create Newsletter app using Mailchimp and Django
In this article, we'll use MailChimp and Django to make a simple mailing app. When people subscribe to our app, we'll learn how to create an audience list and save the users in MailChimp using Python. Have you considered how they could send emails to subscribers with only one click? MailChimp is the greatest email marketing software. It also allows
5 min read
How to Create an App in Django ?
Prerequisite - How to Create a Basic Project using MVT in Django? Django is famous for its unique and fully managed app structure. For every functionality, an app can be created like a completely independent module. This article will take you through how to create a basic app and add functionalities using that app.For example, if you are creating a
4 min read
Adding Tags Using Django-Taggit in Django Project
Django-Taggit is a Django application which is used to add tags to blogs, articles etc. It makes very easy for us to make adding the tags functionality to our django project.Setting up Django Project Installing django-taggit pip install django-taggitADD it to Main Project's settings.py file C/C++ Code INSTALLED_APPS = [ 'django.contrib.admin', 'dja
2 min read
How to customize Django forms using Django Widget Tweaks ?
Django forms are a great feature to create usable forms with just few lines of code. But Django doesn't easily let us edit the form for good designs. Here, we will see one of the ways to customize Django forms, So they will look according to our wish on our HTML page. Basically we will check the methods to include our own custom css, classes, or id
3 min read
Integrating Django with Reactjs using Django REST Framework
In this article, we will learn the process of communicating between the Django Backend and React js frontend using the Django REST Framework. For the sake of a better understanding of the concept, we will be building a Simple Task Manager and go through the primary concepts for this type of integration between React js and Django. Reactjs in a nuts
15+ min read
Using Counter() in Python to find minimum character removal to make two strings anagram
Given two strings in lowercase, the task is to make them Anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. Examples: Input : str1 = "bcadeh" str2 = "hea" O
3 min read
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 = GeeksforGeeks : s2 = rteksfoGrdsskGeggehes Outpu
2 min read
Python | Minimum number of subsets with distinct elements using Counter
You are given an array of n-element. You have to make subsets from the array such that no subset contain duplicate elements. Find out minimum number of subset possible. Examples: Input : arr[] = {1, 2, 3, 4} Output :1 Explanation : A single subset can contains all values and all values are distinct Input : arr[] = {1, 2, 3, 3} Output : 2 Explanatio
4 min read
Anagram checking in Python using collections.Counter()
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Examples: Input : str1 = “abcd”, str2 = “dabc” Output : True Input : str1 = “abcf”, str
2 min read
Weather app using Django | Python
In this tutorial, we will learn how to create a Weather app that uses Django as backend. Django provides a Python Web framework based web framework that allows rapid development and clean, pragmatic design. Basic Setup - Change directory to weather – cd weather Start the server - python manage.py runserver To check whether the server is running or
2 min read
Wikipedia search app Project using Django
Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. Today we will create joke app in django. In this article we will make
2 min read
Translator App Project using Django
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source. Refer to the following articles to check how to cre
2 min read
Deploying a Django App to Heroku Using Github Repository
Heroku is a free hosting cloud service provider. We can use our free dynos to deploy our applications on the cloud. The only disadvantage is that it loses all the data once the app sleeps and it cannot handle multiple requests at a time when hosted on free dynos. First of all, to proceed further you need to have these two things ready Django appHer
2 min read
Build Calculator App Using Django
In this article, we will guide you through the process of creating a calculator app using Django. Our goal is to develop a versatile application capable of performing fundamental mathematical operations such as addition, subtraction, multiplication, and more. By the end of this tutorial, you will have a functional calculator that goes beyond the ba
3 min read
Language Learning App using Django
In this article, we will guide you through creating a language-learning application using Django in Python. Language Learning App Using DjangoBelow, is the step-by-step Implementation of a language learning app using Django in Python: Starting the Project FolderTo start the project use this command django-admin startproject language_appcd language_
15 min read
Realtime chat app using Django
Chat Room has been the most basic step toward creating real-time and live projects. The chat page that we will create will be a simple HTML boilerplate with a simple h1 text with the name of the current user and a link to log out to the user who is just logged in. You may need to comment on the line until we create auth system for this. This ensure
11 min read
Note-taking App using Django
In this article, we will explore a note-making app. In this article, we will create a note-making app using Django. We will also use the Django authentication system. Users need to create an account on the web to access the note-making app. After that, users will have access to the note-making app. This means users can create notes, update them wit
8 min read
Styling Django Forms with django-crispy-forms
Django by default doesn't provide any Django form styling method due to which it takes a lot of effort and precious time to beautifully style a form. django-crispy-forms solves this problem for us. It will let you control the rendering behavior of your Django forms in a very elegant and DRY way. Modules required:django : django installdjango-crispy
1 min read
How to Fix Django "ImportError: Cannot Import Name 'six' from 'django.utils'"?
After Django 3.0, django.utils.six was removed. The "ImportError: Cannot Import Name 'six' from 'django.utils'" error occurs because of the dependency issue. This happens because when the project tries to use something that’s no longer available. Don’t worry—it’s easy to fix. We’ll explain why this error happens and give you simple steps to solve i
3 min read
Python dictionary, set and counter to check if frequencies can become same
Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string. Examples: Input : str = “xyyz” Output : Yes We can remove character ’y’ from above string to make the frequency of each character same. Input : str =
2 min read
Dictionary and counter in Python to find winner of election
Given an array of names of candidates in an election. A candidate name in the array represents a vote cast to the candidate. Print the name of candidates received Max vote. If there is tie, print a lexicographically smaller name. Examples: Input : votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny",
3 min read
Python Counter to find the size of largest subset of anagram words
Given an array of n string containing lowercase letters. Find the size of largest subset of string which are anagram of each others. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Examples: Input: ant magenta magnate tan
5 min read
Python Counter| Find duplicate rows in a binary matrix
Given a binary matrix whose elements are only 0 and 1, we need to print the rows which are duplicate of rows which are already present in the matrix. Examples: Input : [[1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 1]] Output : (1, 1, 0, 1, 0, 1) (0, 0, 1, 0, 0, 1) We have existi
2 min read
Python Counter | Majority Element
Majority Element: A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element). Write a function which takes an array and emits the majority element (if it exists), otherwise prints NONE as follows: Examples: Input : 3 3 4 2 4 4 2 4 4 Output : 4 Input : 3 3 4 2 4 4 2 4 Out
2 min read
Python Counter.update() Method
Python's Counter is a subclass of the dict class and provides a convenient way to keep track of the frequency of elements in an iterable. The Counter.update() method is particularly useful for updating the counts of elements in a Counter object based on another iterable or another Counter object. In this article, we will understand about the Counte
2 min read
Python | Counter Objects | elements()
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python's general-purpose built-ins like dictionaries, lists, and tuples. Counter is a sub-class that is used to count hashable objects. It im
6 min read
Python | Django News App
Django is a high-level framework which is written in Python which allows us to create server-side web applications. In this article, we will see how to create a News application using Django. We will be using News Api and fetch all the headline news from the api. Read more about the api here news api.Do the Following steps in command prompt or term
2 min read
Practice Tags :