Python Forum
TypeError: missing 1 required positional argument (word counter Django app)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
TypeError: missing 1 required positional argument (word counter Django app)
#1
I’ve got a Python script which counts and prints the number of words in a text file. The script runs beautifully. It takes a public domain book (a text file such as Alice and Wonderland) which then counts the top 10 most used words (but which also filters out stopwords). See here for some of my previous work.

Now I am trying to ‘port’ this Python shell script to Django. My intention for this project is to have the Django app count the number of words in a blog post. But for now I’m still using Alice and Wonderland in .txt format.

I’ve encountered some issues with my local dev server running but serving me a series of name errors involving my views module when I navigate to the url. I was hoping some of you could provide some insight.

When I run the server and navigate to http://127.0.0.1:8000/seth/, this is the error showing in my web browser pointing to the issue at hand:
Error:
TypeError at /seth/ counters() missing 1 required positional argument: 'text' Request Method: GET Request URL: http://127.0.0.1:8000/seth/ Django Version: 2.2 Exception Type: TypeError Exception Value: counters() missing 1 required positional argument: 'text' Exception Location: /home/<user>/dev/projects/python/2018-and-2019/CC_Redact_Iter2/venv/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response, line 113 Python Executable: /home/<user>/dev/projects/python/2018-and-2019/CC_Redact_Iter2/venv/bin/python3 Python Version: 3.7.3 Python Path: ['/home/<user>/dev/projects/python/2018-and-2019/CC_Redact_Iter2', '/home/<user>/dev/projects/python/2018-and-2019/CC_Redact_Iter2/venv/lib/python37.zip', '/home/<user>/dev/projects/python/2018-and-2019/CC_Redact_Iter2/venv/lib/python3.7', '/home/<user>/dev/projects/python/2018-and-2019/CC_Redact_Iter2/venv/lib/python3.7/lib-dynload', '/usr/lib64/python3.7', '/usr/lib/python3.7', '/home/<user>/dev/projects/python/2018-and-2019/CC_Redact_Iter2/venv/lib/python3.7/site-packages'] Server time: Wed, 10 Jul 2019 16:00:53 +0000
Here is the traceback from my local Django dev server in my shell:
Error:
$ python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 10, 2019 - 16:17:40 Django version 2.2, using settings 'CC_Redact_Iter2.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /seth/ Traceback (most recent call last): File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact_Iter2/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact_Iter2/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/<user>/dev/projects/python/2018-and-2019/CC_Redact_Iter2/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: counters() missing 1 required positional argument: 'text' [10/Jul/2019 16:17:46] "GET /seth/ HTTP/1.1" 500 67060
The file with the most problems is my counters/views.py (current app only):

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from collections import Counter
from nltk.corpus import stopwords
import re
# from .forms import UploadFileForm
from django.views.generic.edit import FormView
from .forms import FileFieldForm

text = None
word = None

class FileFieldView(FormView):
    form_class = FileFieldForm
    template_name = 'seth.html'  # Replace with your template.
    success_url = 'seth_success' # Replace with your URL or reverse().

    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        files = request.FILES.getlist('Alice.txt')
        if form.is_valid():
            for f in files:
                global text
                # Do something with each file. For example the following? Is what follows even valid?
                text = f.read().lower()                
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

def counters(request, text):
    """
    This function processes the top 10 most common words and then renders them.
    """
    stoplist = stopwords.words('english')
    stoplist.extend(["said","gutenberg", "could", "would",]) 
    clean = []
    global word
    global count
    for word in re.split(r"\W+",text):
        if word not in stoplist:
            clean.append(word)
    top_10 = Counter(clean).most_common(10)
    for word,count in top_10:
        return render(request, 'counters/seth.html', {'word': word, 'count': count})

def main(request):
    """
    This function calls the counters function
    """
    text = FileFieldView.post()
    run = counters(text)

if __name__ == "__main__":
    main()
    pass
I realize that the problem is with the way the text variable is tossed around. I probably should not be invoking global variables as I do at lines 24, 38, 39 in my views model (above). Furthermore, out of the Udemy course material I’ve watched and in the official Django docs I’ve read, I’ve never seen a views.py which uses main() for calling functions. I realize I am sort of departing from Django norms here. What might you people recommend I try instead?

Here is counters/models.py:

from django.db import models
from django import forms
import datetime

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=150)
    file = forms.FileField()

class Count(models.Model):
    title = models.CharField(max_length=161)
    pub_date = models.DateTimeField()
    image = models.ImageField(upload_to='media/')
    body = models.TextField()
    now = datetime.datetime.now()

class FileFieldForm(forms.Form):
    file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
Here is counters/forms.py:

# With advice from this Django doc: https://docs.djangoproject.com/en/2.2/topics/http/file-uploads/
 
from django import forms

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file = forms.FileField()

class FileFieldForm(forms.Form):
    file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
Here is urls.py in parent project directory:

from django.contrib import admin
from django.urls import path, re_path
# from . import views
from posts.views import *
from redactors.views import *
from counters.views import *
from AllAbove.views import *
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
   path('admin/', admin.site.urls),
   path('', home, name='home'),
   path('result/', result, name='result'),
   path('seth/', counters, name='seth'),
   #path('james/', post_details, name='james'),
   path('maggie/', maggie_post_details, name='maggie'),
   path('AllAbove/', all_above, name='AllAbove'),
   re_path(r'^posts/(?P<post_id>[0-9]+)/$', post_details, name='james'),
   path('simon/', redactors, name='simon'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Here is Alice and Wonderland in .txt format

What other comments might you have about my code, in particular the views.py linked to above?

I’m running Django 2.2 and Python 3.7 on Manjaro.

Pull requests on GitHub (my repo can be found here) are welcome although I realize if asking for pull requests like this might not be reasonable for most of you but I thought I’d say as always, just in case a kind and generous forum contributor has time on their hands. Requirements.txt is included on the master branch.

For what it is worth, here is some of the documentation I’ve been working with.

I’ve referred to official Django docs for:
Stack Overflow questions I’ve used:
Reply
#2
https://github.com/Angeles4four/CC_Redac...ews.py#L31

The counters view has two parameters. One, request is provided by Django. The other, text would come from the user via a url param or post param (ie: http://url/seth?text=blah+blah or http://url/seth/blah+blah). Without that param, the counters view is being called without a value for text, which is an error.

ie: you're NOT using global variables here. You could solve your issue by having a default param for texts (def counters(request, text=""): for example), or by just not calling it without a payload.
Reply
#3
(Jul-10-2019, 07:18 PM)nilamo Wrote: ie: you're NOT using global variables here. You could solve your issue by having a default param for texts (def counters(request, text=""): for example), or by just not calling it without a payload.

Calling the counters function passing the text variable without a payload using ="" as you suggested successfully eliminates the TypeError.

I'll return here soon if I have any further questions as I continue coding my Django app. Wink

Thanks @nilamo for your help so far, my friend!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Shocked Django __init__() got an unexpected keyword argument 'any' ikurorox 2 5,381 Nov-26-2021, 07:57 PM
Last Post: ikurorox
  Django views : positional argument ghoul 0 1,423 Nov-15-2021, 06:02 PM
Last Post: ghoul
  TypeError: to_capabilities() missing 1 required positional argument: 'self' OceansBlue 2 5,191 Dec-03-2020, 12:08 AM
Last Post: OceansBlue
  Django: How to automatically substitute a variable in the admin page at Django 1.11? m0ntecr1st0 3 3,245 Jun-30-2019, 12:21 AM
Last Post: scidam
  word counter kid_with_polio 3 2,748 Jun-19-2019, 11:26 PM
Last Post: Yoriz
  TypeError("index() missing 1 required positional argument: 'pymydb'" nikos 2 4,197 Mar-03-2019, 09:21 PM
Last Post: micseydel
  [split] [Help] Keep getting a 'TypeError' from Django and BeautifulSoup moxasya 0 2,156 Nov-15-2018, 07:38 AM
Last Post: moxasya
  TypeError: get_names() takes 0 positional arguments but 1 was given Truman 2 10,162 Aug-15-2018, 10:32 PM
Last Post: Truman
  [Help] Keep getting a 'TypeError' from Django and BeautifulSoup Plant_Boy 7 5,508 Jun-13-2018, 04:13 PM
Last Post: Larz60+
  first django site-ms word/pdf files jon0852 1 4,345 Nov-19-2017, 08:39 PM
Last Post: homayoon_hashemi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020