Search code examples
pythondjangodjango-viewspython-module

Undefined variable error during splitting views.py into modules - Django


My codes in views.py becomes larger day by day, and now I want to split it into modules. But I have trouble with variables. Problem is in that I don't where should I declare variables, or import built-in modules: in my custom module, or views.py. Here is my codes:

views.py:

@login_required(login_url='sign_in')
def result(request):
    find_by_fives()
    context = {
        'last_uploaded': last_uploaded,
        'words_count': words_count,
        'characters_count': characters_count
    }
    return render(request, 'result.html', context)

find_by_fives.py(is my custom module):

import glob 
from .models import OriginalDocument
from django.shortcuts import render

def find_by_fives():
    last_uploaded = OriginalDocument.objects.latest('id')

    original = open(str(last_uploaded.document), 'r')
    original_words = original.read().lower().split()
    words_count = len(original_words)

    open_original = open(str(last_uploaded.document), "r")
    read_original = open_original.read()
    characters_count = len(read_original)

    path = 'static/other_documents/doc*.txt'
    files = glob.glob(path)                       

Error: NameError: name 'last_uploaded' is not defined

Note: This is not my entire view, all I want to know is just where should I declare context, variables, and imports.


Solution

  • Ok, I see - "find_by_fives.py" is a function, right? So the variables that you declare inside it lives only there. So when you call this function from the views.py - they get declared and then, when the function is over they get deleted. If you want to use them in the views.py - you should return them and assign a variable there, then pass them to the context:

    @login_required(login_url='sign_in')
    def result(request):
       last_uploaded, words_count, characters_count = find_by_fives()
       context = {
           'last_uploaded': last_uploaded,
           'words_count': words_count,
           'characters_count': characters_count
       }
       return render(request, 'result.html', context)
    
    def find_by_fives():
       last_uploaded = OriginalDocument.objects.latest('id')
    
       original = open(str(last_uploaded.document), 'r')
       original_words = original.read().lower().split()
       words_count = len(original_words)
    
       open_original = open(str(last_uploaded.document), "r")
       read_original = open_original.read()
       characters_count = len(read_original)
    
       path = 'static/other_documents/doc*.txt'
       files = glob.glob(path) 
       return last_uploaded, words_count, characters_count