将 views.py 拆分为模块时出现未定义变量错误 - Django

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

我在views.py的代码一天比一天大,现在想拆分成模块。但是我在变量方面遇到了麻烦。问题是我不知道我应该在哪里声明变量,或者导入内置模块:在我的自定义模块中,或者 views.py。这是我的代码:

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(是我的自定义模块):

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)                       

错误:NameError: name 'last_uploaded' is not defined

注意:这不是我的全部观点,我只想知道我应该在哪里声明context、变量和导入。

好的,我明白了 - "find_by_fives.py" 是一个函数,对吧?因此,您在其中声明的变量仅存在于其中。因此,当您从 views.py 调用此函数时 - 它们会被声明,然后,当函数结束时,它们会被删除。如果你想在 views.py 中使用它们 - 你应该 return 它们并在那里分配一个变量,然后将它们传递给上下文:

@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