You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求实现带清空与字数统计功能的简易Django表单

Got it, let's keep this simple—no overcomplicated tutorials here. Here's a straightforward way to build your Django form with clear and count buttons:

Step 1: Create a Simple Form

First, define a basic form in your app's forms.py (create this file if you don't have it):

from django import forms

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

Step 2: Update Your View

In your views.py, add logic to handle both button actions and your existing word count function:

from django.shortcuts import render
from .forms import TextInputForm

# Your existing word count function (adjust as needed)
def count_words(text):
    # Simple count: ignore empty strings after splitting
    return len([word for word in text.split() if word.strip()])

def word_counter(request):
    form = TextInputForm()
    word_count_result = None

    if request.method == 'POST':
        form = TextInputForm(request.POST)
        
        # Handle "Count Words" button
        if 'count' in request.POST:
            if form.is_valid():
                input_text = form.cleaned_data['content']
                word_count_result = count_words(input_text)
        
        # Handle "Clear Input" button
        elif 'clear' in request.POST:
            form = TextInputForm()  # Reset to empty form

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

Step 3: Update Your HTML Template

Replace your existing template code with this (make sure to keep the correct path for your template file):

<html>
<head>
    <title>Simple Word Counter</title>
</head>
<body>
    <h2>Text Input & Word Counter</h2>
    
    <form method="post">
        {% csrf_token %}  <!-- Required for Django form security -->
        {{ form.as_p }}  <!-- Renders the textarea input nicely -->
        
        <!-- Two submit buttons with unique names -->
        <button type="submit" name="count">Count Words</button>
        <button type="submit" name="clear">Clear Input</button>
    </form>

    <!-- Display the word count result if it exists -->
    {% if word_count is not None %}
        <p style="margin-top: 15px;">
            Word Count: <strong>{{ word_count }}</strong>
        </p>
    {% endif %}
</body>
</html>

Step 4: Add a URL Pattern

In your app's urls.py, map the view to a URL:

from django.urls import path
from . import views

urlpatterns = [
    path('counter/', views.word_counter, name='word_counter'),
]

That's it! This setup keeps things minimal:

  • The form uses a textarea for easy multi-line input
  • The view checks which button was clicked to either run the count or reset the form
  • The template displays the result clearly without extra fluff

内容的提问来源于stack exchange,提问作者M.K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:23:04