Creating Text Utilities with Django | Uppercase, Lowercase, Word Count & More

Faraz

By Faraz -

Discover how to create a Django app with powerful text utilities. Learn to implement features like Uppercase, Lowercase, Titlecase, Word Count, Language Detection, Word Frequency, and Reverse Text.


creating-text-utilities-with-django-uppercase-lowercase-word-count-and-more.webp

Creating versatile text utilities with Django offers a valuable opportunity to enhance your web development skills. In this tutorial, you'll learn how to build a Django application that includes a range of text manipulation features: converting text to uppercase, lowercase, and titlecase, performing word counts, detecting languages, analyzing word frequency, and reversing text. This comprehensive guide is designed to help both beginners and experienced developers add powerful text-processing capabilities to their Django projects.

Prerequisites

Before we dive in, make sure you have a basic understanding of Django and web development. You'll need the following tools and libraries installed on your machine:

  • Python (version 3.6 or higher)
  • Django (version 3.0 or higher)
  • A text editor or IDE (such as VS Code or PyCharm)
  • Basic knowledge of HTML and CSS

Setting Up the Development Environment

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 textutils_project

Setting up the project structure

Navigate into your project directory:

cd textutils_project

Create a Django App

Create a new app within your project:

python manage.py startapp textutils

Install LangDetect Library

If you haven't installed langdetect, install it using pip:

pip install langdetect

Adding the app to the project

In textutils_project/settings.py, add textutils to the INSTALLED_APPS list:

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

Creating the Text Utilities App

Create Forms for Text Input

In textutils, create a new file named forms.py to handle text inputs from users and add the following function:

from django import forms

class TextInputForm(forms.Form):
    text = forms.CharField(widget=forms.Textarea, label='Enter your text')

Creating the Views

Next, we’ll create views to process text. Open textutils/views.py and add the following:

from django.shortcuts import render
from .forms import TextInputForm
from collections import Counter
from langdetect import detect, DetectorFactory
DetectorFactory.seed = 0


def home(request):
    if request.method == 'POST':
        form = TextInputForm(request.POST)
        if form.is_valid():
            text = form.cleaned_data['text']
            word_count = len(text.split())
            reversed_text = text[::-1]
            uppercase_text = text.upper()
            lowercase_text = text.lower()
            titlecase_text = text.title()

            # Frequency Analysis
            words = text.split()
            frequency = dict(Counter(words))

            # Text Summary (Extracting first 3 sentences)
            sentences = text.split('. ')
            summary = '. '.join(sentences[:3]) if len(sentences) > 3 else text

            # Language Detection
            try:
                language = detect(text)
            except:
                language = "Unable to detect"

            return render(request, 'results.html', {
                'form': form,
                'word_count': word_count,
                'reversed_text': reversed_text,
                'uppercase_text': uppercase_text,
                'lowercase_text': lowercase_text,
                'titlecase_text': titlecase_text,
                'frequency': frequency,
                'summary': summary,
                'language': language,
            })
    else:
        form = TextInputForm()
    return render(request, 'home.html', {'form': form})

Create Templates

Create a templates directory within the textutils app and then create home.html and results.html inside this directory.

Create a template for the homepage in textutils/templates/home.html:

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Text Utilities</title>
    <link rel="stylesheet" href="{% static 'styles.css' %}">
</head>
<body>
    <div class="container">
        <h1>Text Utilities</h1>
        <form method="post" class="form-container">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit" class="submit-btn">Submit</button>
        </form>
    </div>
</body>
</html>

In textutils/templates/results.html, display the results:

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Text Utilities Results</title>
    <link rel="stylesheet" href="{% static 'styles.css' %}">
</head>
<body>
    <div class="container">
        <h1>Results</h1>
        <div class="results-container">
            <p><strong>Word Count:</strong> {{ word_count }}</p><br />
            <p><strong>Titlecase Text:</strong> <pre>{{ titlecase_text }}</pre></p>
            <p><strong>Uppercase Text:</strong> <pre>{{ uppercase_text }}</pre></p>
            <p><strong>Lowercase Text:</strong> <pre>{{ lowercase_text }}</pre></p>
            <p><strong>Reversed Text:</strong> <pre>{{ reversed_text }}</pre></p>
            <h2>Word Frequency</h2>
            <ul class="frequency-list">
                {% for word, count in frequency.items %}
                    <li><strong>{{ word }}:</strong> {{ count }}</li>
                {% endfor %}
            </ul>
            <h2>Text Summary</h2>
            <p>{{ summary }}</p>
            <h2>Detected Language</h2>
            <p>{{ language }}</p>
            <a href="{% url 'home' %}" class="back-btn">Back</a>
        </div>
    </div>
</body>
</html>

Add CSS Styling

Create a CSS file named styles.css in textutils/static/ and add the following styles:

body, h1, p, ul {
    margin: 0;
    padding: 0;
}

body {
    font-family: 'Arial', sans-serif;
    background: linear-gradient(135deg, #f5f7fa, #c3cfe2);
    color: #333;
    line-height: 1.6;
    padding: 20px;
}

.container {
    max-width: 900px;
    margin: 0 auto;
    background: #ffffff;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

h1 {
    text-align: center;
    color: #333;
    margin-bottom: 20px;
    font-size: 2.5rem;
}

.form-container {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.form-container input, .form-container textarea {
    border: 2px solid #ddd;
    border-radius: 8px;
    padding: 15px;
    font-size: 16px;
    transition: border-color 0.3s ease, box-shadow 0.3s ease;
    width: 100%;
    box-sizing: border-box;
}

.form-container textarea {
    height: 200px;
    resize: none; 
}

.form-container input:focus, .form-container textarea:focus {
    border-color: #007bff;
    box-shadow: 0 0 8px rgba(0, 123, 255, 0.5);
    outline: none;
}

.submit-btn {
    background: #007bff;
    color: #fff;
    border: none;
    border-radius: 8px;
    padding: 15px;
    cursor: pointer;
    font-size: 18px;
    transition: background 0.3s ease, transform 0.3s ease;
}

.submit-btn:hover {
    background: #0056b3;
    transform: scale(1.02);
}

.results-container {
    margin-top: 20px;
}

.results-container pre {
    background: #f5f5f5;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 15px;
    overflow: auto;
    white-space: pre-wrap;
}

.frequency-list {
    list-style: none;
    padding: 0;
}

.frequency-list li {
    padding: 10px 0;
    border-bottom: 1px solid #ddd;
}

.frequency-list li:last-child {
    border-bottom: none;
}

.back-btn {
    display: inline-block;
    margin-top: 20px;
    background: #28a745;
    color: #fff;
    padding: 15px 25px;
    border-radius: 8px;
    text-decoration: none;
    font-size: 18px;
    transition: background 0.3s ease, transform 0.3s ease;
}

.back-btn:hover {
    background: #218838;
    transform: scale(1.05);
}

@media (max-width: 768px) {
    .container {
        padding: 10px;
    }
    
    .submit-btn, .back-btn {
        width: 100%;
    }
}

Include Static Files

Make sure Django is configured to serve static files in development. Ensure you have these settings in textutils_project/settings.py:

STATIC_URL = '/static/'

Set Up URL Routing

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

from django.urls import path
from . import views

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

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

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

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

Run Your Server

Apply migrations and run your server:

python manage.py migrate
python manage.py runserver

Open your browser and go to http://127.0.0.1:8000/ to use the text utilities.

Full Text Utilities App Project Structure

textutils_project/
    ├── textutils/
    │   ├── migrations/
    │   ├── static/
    │   │       └── styles.css
    │   ├── templates/
    │   │       ├── home.html
    │   │       └── results.html
    │   ├── __init__.py
    │   ├── admin.py
    │   ├── apps.py
    │   ├── forms.py
    │   ├── models.py
    │   ├── tests.py
    │   ├── urls.py
    │   └── views.py
    ├── textutils_project/
    │   ├── __init__.py
    │   ├── asgi.py
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    ├── manage.py

Conclusion

By following this tutorial, you've equipped yourself with the skills to create a feature-rich text utility application using Django. You’ve learned how to implement functions for uppercase, lowercase, and titlecase conversion, word counting, language detection, word frequency analysis, and text reversal. These features not only make your application more robust but also demonstrate the versatility of Django in handling various text-related tasks. Continue to explore and refine these techniques to build even more sophisticated applications.

Feel free to make any further adjustments based on your preferences or additional details!

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🥺