Create Word Counter App using Django (original) (raw)

Last Updated : 8 Apr, 2026

Our task is to build a simple Django application that counts the number of words in a given text. This is a great beginner project if you have some basic knowledge of Django.

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

Step 1: Create the Word Counting Logic in Views

First, we create a function called **counter in **views.py which will handle the logic for counting words:

Python `

from django.shortcuts import render

def counter(request): if request.method == 'POST':

    text = request.POST['texttocount']

    if text != '':
        word = len(text.split())
        i = True
        return render(request, 'counter.html',
                      {'word': word,
                      'text': text,
                      'i': i, 
                      'on': 'active'
        })

    else:
        return render(request, 'counter.html', {'on': 'active'})
else:
    return render(request, 'counter.html', {'on': 'active'})

`

**Explanation:

Step 2: Configure URL Patterns

In your app's **urls.py, map the URL ****/counter** to your **counter view:

Python `

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'), ]

`

Then include your app URLs in the main project **urls.py:

Python `

from django.contrib import admin from django.urls import path, include from django.views.generic import RedirectView

urlpatterns = [ path('admin/', admin.site.urls), path('', RedirectView.as_view(url='counter', permanent=False)), # Redirect root to /counter path('myapp/', include('yourappname.urls')), # Replace yourappname with your actual app name ]

`

Step 3: Create the HTML Template

Create a file called **counter.html inside your app’s templates folder and add the following code:

HTML `

{% if i %}

{{ word }} Word{{ word|pluralize }} in the text

{% endif %}
{% csrf_token %}
Paste your text here
<div class="text-center">
  <!-- Ads or other content can go here -->
</div>

<div class="form-group text-center">
  <button type="submit" class="btn btn-primary w-25">Run Counter</button>
</div>

`

**Notes:

Step 4: Run Your Application

Make sure your Django server is running:

python manage.py runserver

**Output:

TemplateDoesNotExist at /counter