Create a simple Django web application
Application includes a single textbox. When the user enters text, the application will calculate the number of characters and display the result on the same webpage.
Create a Django Project and App:
First, create a new Django project and a new app within the project.
Let’s call the app character_counter.
Create a View and Template:
In your views.py, create a view that handles the form submission and calculates the character count.
Create an HTML template (index.html) to display the form and the result.
Define Your View and Template:
Python
# character_counter/views.py
from django.shortcuts import render
def character_count(request):
if request.method == 'POST':
user_text = request.POST.get('user_text', '')
char_count = len(user_text)
return render(request, 'character_counter/index.html', {'char_count': char_count})
return render(request, 'character_counter/index.html')
HTML
<!-- character_counter/templates/character_counter/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Character Counter</title>
</head>
<body>
<h1>Character Counter</h1>
<form method="post">
{% csrf_token %}
<input type="text" name="user_text" placeholder="Enter text">
<input type="submit" value="Count Characters">
</form>
{% if char_count %}
<p>Character count: {{ char_count }}</p>
{% endif %}
</body>
</html>
URL Configuration: Set up the URL pattern in your app’s urls.py:
Python
# character_counter/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.character_count, name='character_count'),
]
Run the Development Server: Run python manage.py runserver to start the development server.
Visit http://localhost:8000/ to see the character counter in action.