Build a Word Counter in Django | Simple Django Tutorial

Faraz

By Faraz - July 29, 2024

Learn how to create a word counter in Django with this easy tutorial. Step-by-step guide for beginners.


build-a-word-counter-in-django-simple-django-tutorial.webp

Creating a word counter in Django is a practical project for beginners looking to learn web development with this powerful framework. This step-by-step guide will walk you through building a simple word counter application using Django. Whether you're new to Django or want to sharpen your skills, this tutorial will help you understand the basics of form handling, views, and templates. By the end, you'll have a functional web app that counts the number of words in user-provided text.

Prerequisites

Before diving into the code, make sure you have a basic understanding of Django and some familiarity with Python. Here’s what you need:

  • Python installed on your computer
  • Basic knowledge of Django framework
  • A code editor (VS Code, PyCharm, etc.)

Setting Up Your Django Project

Installing Django

Before starting, ensure you have Python installed. You can install Django using pip:

pip install django

Creating a new Django project

Create a new Django project using the following command:

django-admin startproject wordcounter

Setting up the project structure

Navigate into your project directory:

cd wordcounter

Create a Django App

Create a new app within your project:

python manage.py startapp counter

Adding the app to the project

Add counter to INSTALLED_APPS in wordcounter/settings.py:

INSTALLED_APPS = [
    'counter',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Building the Word Counter App

Create Forms

In counter, create a new file named forms.py and add the following function:

from django import forms

class TextInputForm(forms.Form):
    text = forms.CharField(widget=forms.Textarea(attrs={'rows': 10, 'cols': 40, 'placeholder': 'Enter your text here...'}), label='')

Creating a View for Word Counter

Create a view to handle the form and count words. In counter/views.py, add the following code:

from django.shortcuts import render
from .forms import TextInputForm


def count_words(request):
    word_count = None
    form = TextInputForm(request.POST or None)

    if request.method == 'POST' and form.is_valid():
        text = form.cleaned_data['text']
        word_count = len(text.split())

    return render(request, 'count_words.html', {'form': form, 'word_count': word_count})

Creating Templates

Create a template to render the form and display the word count. Create a file named count_words.html in counter/templates/:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Word Counter</title>
    <style>
body {
    font-family: 'Roboto', sans-serif;
    background-color: #e0f7fa;
    color: #333;
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}
.container {
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
    padding: 30px;
    width: 90%;
    max-width: 600px;
    text-align: center;
}
h1 {
    color: #00796b;
    font-size: 2.5rem;
    margin: 0;
}
form {
    display: flex;
    flex-direction: column;
    align-items: center;
}
textarea {
    border: 2px solid #00796b;
    border-radius: 8px;
    padding: 15px;
    font-size: 1rem;
    width: 100%;
    max-width: 100%;
    height: 200px;
    resize: none;
    margin-bottom: 20px;
}
button {
    background-color: #00796b;
    border: none;
    border-radius: 8px;
    color: white;
    font-size: 1.1rem;
    padding: 12px 20px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}
button:hover {
    background-color: #004d40;
}
.result {
    margin-top: 20px;
    padding: 15px;
    border-radius: 8px;
    background-color: #b2dfdb;
    font-size: 1.2rem;
}
    </style>
</head>
<body>
    <div class="container">
        <h1>Word Counter</h1>
        <form method="post">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Count Words</button>
        </form>
        {% if word_count is not None %}
            <div class="result">
                <h2>Word Count: {{ word_count }}</h2>
            </div>
        {% endif %}
    </div>
</body>
</html>

Set Up URL Routing

Add a URL pattern for your view. In counter/urls.py (create this file if it doesn't exist), add:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.count_words, name='count_words'),
]

Include the app's URLs in your project's URL configuration. Open wordcounter/urls.py and include the counter app URLs:

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

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

Run Your Server

Apply migrations and run your server:

python manage.py migrate
python manage.py runserver

Visit http://127.0.0.1:8000/ in your web browser. You should see the word counter form. Enter some text and submit to see the word count.

Full Word Counter Project Structure

wordcounter/
├── counter/
│   ├── migrations/
│   │   ├── __init__.py
│   ├── templates/
│   │       └── count_words.html
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── forms.py
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── wordcounter/
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── db.sqlite3
└── manage.py

Conclusion

You've successfully built a word counter application using Django. This project has introduced you to fundamental Django concepts such as form handling and template rendering. By following this guide, you now have a solid understanding of how to create and manage user input in Django. Feel free to expand this project by adding more features or integrating it into a larger application.

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺