Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Speak the meaning of the word using Python
Next article icon

Our task is to build a simple Django application that counts the number of words in a given text. This is a great beginner project if you have some basic knowledge of Django.

Refer to the below article to know about basics of Django.

Step 1: Create the Word Counting Logic in Views

First, we create a function calledcounterinviews.py which will handle the logic for counting words:

Python
fromdjango.shortcutsimportrenderdefcounter(request):ifrequest.method=='POST':text=request.POST['texttocount']iftext!='':word=len(text.split())i=Truereturnrender(request,'counter.html',{'word':word,'text':text,'i':i,'on':'active'})else:returnrender(request,'counter.html',{'on':'active'})else:returnrender(request,'counter.html',{'on':'active'})

 Explanation:

  • When the user submits text via POST, we check if the input is not empty.
  • We then split the text by spaces and count the resulting words.
  • If successful, we pass the word count and original text back to the template.
  • On GET requests or empty input, we simply render the form without results.

Step 2: Configure URL Patterns

In your app'surls.py, map the URL/counter to yourcounterview:

Python
fromdjango.urlsimportpathfrom.importviewsfromdjango.confimportsettingsfromdjango.conf.urls.staticimportstaticurlpatterns=[path('counter',views.counter,name='counter'),]

Then include your app URLs in the main projecturls.py:

Python
fromdjango.contribimportadminfromdjango.urlsimportpath,includefromdjango.views.genericimportRedirectViewurlpatterns=[path('admin/',admin.site.urls),path('',RedirectView.as_view(url='counter',permanent=False)),# Redirect root to /counterpath('',include('yourappname.urls')),# Replace yourappname with your actual app name]

Step 3: Create the HTML Template

Create a file calledcounter.html inside your app’s templates folder and add the following code:

HTML
{% if i %}<divclass="mb-2"style="border-style: groove; border-radius: 10px;"><divclass="card-header"><pstyle="font-size: 20px;">{{ word }} Word{{ word|pluralize }} in the text</p></div></div>{% endif %}<divclass="col-12 pb-3"style="background-color: #c2d6d6; border: 2px groove; border-radius: 10px;"><formaction="counter"method="POST">    {% csrf_token %}<divclass="form-group"><labelfor="text1">Paste your text here</label><textareaname="texttocount"id="text1"rows="8"style="background-color: #f0f5f5;"class="form-control"placeholder="Enter text to count words">{{ text }}</textarea></div><divclass="text-center"><!-- Ads or other content can go here --></div><divclass="form-group text-center"><buttontype="submit"class="btn btn-primary w-25">Run Counter</button></div></form></div>

Notes:

  • The{% csrf_token %} tag is essential for POST requests to pass Django’s CSRF protection.
  • We conditionally display the word count only when the counting process has succeeded (i is true).
  • {{ word|pluralize }}adds an “s” when the word count is more than one for proper grammar.

Step 4: Run Your Application

Make sure your Django server is running:

python manage.py runserver

Output:

TemplateDoesNotExist at /counter

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp