Jul-10-2019, 05:22 PM
(This post was last modified: Jul-10-2019, 10:12 PM by Drone4four.)
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
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:
Here is counters/forms.py:
Here is urls.py in parent project directory:
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:
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): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
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 |
Here is counters/models.py:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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 })) |
1 2 3 4 5 6 7 8 9 10 |
# 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 })) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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) |
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: