亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 views.py 拆分為模塊時出現未定義的變量錯誤

將 views.py 拆分為模塊時出現未定義的變量錯誤

aluckdog 2022-09-13 10:19:53
我的代碼一天比一天大,現在我想把它分成模塊。但我在變量方面遇到了麻煩。問題在于,我不應該在哪里聲明變量,或者導入內置模塊:在我的自定義模塊中,或者.這是我的代碼:views.pyviews.pyviews.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 OriginalDocumentfrom django.shortcuts import renderdef 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
查看完整描述

1 回答

?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

好的,我看到了 - “find_by_fives.py”是一個功能,對吧?因此,您在其中聲明的變量僅存在于其中。因此,當您從 views.py 調用此函數時 - 它們被聲明,然后,當函數結束時,它們將被刪除。如果要在 views.py 中使用它們 - 您應該返回它們并在那里分配一個變量,然后將它們傳遞給上下文:


@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 


查看完整回答
反對 回復 2022-09-13
  • 1 回答
  • 0 關注
  • 93 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號