Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 77 ยท Projects

Project: Word Counter and CGPA Calculator

Build two small Django apps without a database: a word counter with a form and a CGPA calculator with a formset, learning validation, pure functions and tests.

Not every useful web app stores data. A word counter takes some text and shows statistics. A CGPA calculator takes a list of courses and grades and shows a number. Both are model-less: no tables, no migrations, no admin. They are a good way to practice the part of Django that sits between the browser and your logic: forms, validation, views and templates.

These projects also teach a habit that scales to big applications: put the real work in a pure function (analyse(), calculate_gpa()) that takes plain values and returns plain values, and keep the view thin. A pure function is trivial to test and has nothing to do with HTTP.

You should know Django forms, form validation and handling forms in views. Both examples below run for real: they send form submissions to the view with Django's test client and print what comes back.

The recipe for a model-less tool

flowchart LR
    B["Browser form"] --> V["View"]
    V --> F{"Form valid?"}
    F -- no --> E["Re-render with errors"]
    F -- yes --> P["Pure function<br/>does the work"]
    P --> R["Template shows the result"]

The view only wires things together. Validation lives in the form; the calculation lives in a function.

  1. Write a form that describes the input and its rules.
  2. Write a pure function for the calculation.
  3. Write a view that builds the form (request.POST or None), calls the function when the form is valid, and renders a template.
  4. Add the URL.

There is no redirect after a successful submit here, because the result is the response and nothing was saved. That is a deliberate exception to the "post, redirect, get" rule from Handling Forms in Views: if the page changed server data, you would redirect.

Project 1: Word counter

The form has a large text area, with max_length to avoid a 50 MB paste, and an "ignore case" checkbox. The pure function counts words with a regular expression (so punctuation does not stick to words), characters with and without spaces, sentences, an estimated reading time (about 200 words per minute is a common figure) and the three most frequent words, skipping a few filler words such as "the" and "and".

Python Word counter: form, pure function and view

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check the details. An empty submission shows a custom error message (set with error_messages), and the view never calls analyse(). The sample text has 16 words, and "django" appears three times, so it tops the list while the other words tie. With ignore_case=False, Apple, apple and APPLE are counted separately, which is why that checkbox exists.

Ideas to extend it:

  • Use str.split() for a simpler word definition, and compare the results on text with hyphens and apostrophes to see why the regex is better.
  • Add a "longest word" statistic or a character frequency table.
  • Accept an uploaded .txt file with a FileField (see Static Files and Media); read it as UTF-8 and pass the string to analyse() unchanged. That is the reward for keeping the function pure.
  • Return the result as JSON with JsonResponse to build a live-updating counter with JavaScript.

Project 2: CGPA calculator

A GPA (grade point average) weights each course's grade points by its credits: sum(credits x points) / sum(credits). A CGPA (cumulative GPA) is the same weighted average over all semesters. The number of courses varies, so one form is not enough: you need a formset, a group of identical forms with a management form that tracks how many rows were submitted.

Two Django features do the heavy lifting:

  • formset_factory(CourseForm, extra=3) produces a class that renders three blank rows. The posted data carries form-TOTAL_FORMS, form-INITIAL_FORMS and similar hidden fields; without them Django raises a ValidationError about "ManagementForm data is missing", the usual first error with formsets.
  • A custom BaseFormSet.clean() checks rules across rows, such as "at least one course."

Credits and grade points are fractional, so the code uses Decimal, never float, and rounds half up to two places. (See Models and Fields on DecimalField for the same reasoning applied to money.)

Python CGPA calculator: formset, validation and Decimal arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The five test cases cover the interesting paths:

Case Behavior Rule that produced it
three courses 31.0 points over 10 credits is 3.10 the weighted average
empty rows are ignored the blank middle row did not break anything rows with no credits are skipped
half-filled row "Enter both credits and a grade..." the form's clean()
nothing entered "Add at least one course." the formset's clean()
bad credits a field error and the half-row error min_value, then clean()

The last line shows the CGPA across two semesters as a credit-weighted average ((10 x 3.20 + 12 x 3.60) / 22 = 3.42), not the average of the two GPAs (3.40). Averaging averages is a classic bug.

Ideas to extend it:

  • Let users pick a grading scale (4.0, 10-point, percentage) by passing a dictionary into the form and the function.
  • Add an "add row" button with a few lines of JavaScript that clones a form and increments form-TOTAL_FORMS, or use a larger extra= and ignore empty rows as the example does.
  • Remember the user's last semester in the session (see Sessions and Cookies) so the page works across visits without an account.
  • Add a "what do I need next semester to reach 3.5?" calculator: algebra on the same weighted-average formula.

Test the pure functions

Because the logic is plain Python, tests are short and fast, with no client and no database:

Python
# tests.py (read-only)
from decimal import Decimal
from django.test import SimpleTestCase
from .views import analyse, calculate_gpa


class UtilityTests(SimpleTestCase):
    def test_word_counter_ignores_punctuation(self):
        stats = analyse("Hello, hello! World.")
        self.assertEqual(stats["summary"]["words"], 3)
        self.assertEqual(stats["top_words"][0], ("hello", 2))

    def test_gpa_is_weighted_by_credits(self):
        result = calculate_gpa([(Decimal("4"), "A"), (Decimal("1"), "F")])
        self.assertEqual(result["gpa"], Decimal("3.20"))

SimpleTestCase skips the database setup entirely, which is why these run in milliseconds. A smaller set of tests with the test client should then confirm that the view validates input and shows errors, as the examples above did. See Testing Django Apps.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why put the calculation in a pure function instead of the view?

    A pure function takes plain values and returns plain values, so it is easy to test, reuse (for example behind an API) and reason about.
  2. 2. What does a formset need in the submitted data besides the row fields?

    The management form tells Django how many forms were submitted. Without it, validation fails with a management form error.
  3. 3. Why is the CGPA over two semesters not the plain average of the two GPAs?

    A semester with more credits counts for more. Weighting by credits is the correct way to combine them.
  4. 4. Which type should you use for credits and grade points instead of float?

    Decimal gives exact decimal arithmetic and controlled rounding, which avoids surprises like 0.1 + 0.2 != 0.3.

Summary

  • Model-less tools are forms plus a pure function plus a thin view; no tables or migrations are needed.
  • Put validation in the form (field rules and clean()) and cross-row rules in the formset's clean().
  • A formset handles a variable number of rows and needs its management form data.
  • Use Decimal for credits and grades, round explicitly, and combine semesters with a credit-weighted average.
  • Test the pure functions with SimpleTestCase, and keep a few client tests for the form behavior.

Next: Django Exercises with Solutions.