![](/img/trans.png)
[英]How to create a function is views.py so that all the functions inside the views.py can use it
[英]How Can I Run a Function Inside of Views.py and Print Result? — Django
問題是我試圖從views.py調用一個函數,並通過上下文變量將結果打印到模板中。 該功能在終端上打印,在模板中不起作用。 幾天前,我發布了一個關於使用子流程執行此操作的問題,但我仍然無法弄清楚。
如何在模板而不是終端中打印“這是AAPL的測試功能”?
Views.py
from django.shortcuts import render
from backtests.scripts import Backtests
def index(request):
if 'symbol' in request.GET:
symbol = request.GET.get('symbol','Invalid Symbol')
request.session['symbol'] = symbol
else:
symbol = request.session['symbol']
earnings_object = Backtests("AAPL")
test = earnings_object.print_discrep()
return render(request, 'backtests/earnings.html', {'symbol':symbol, 'test':test})
scripts.py
class Backtests:
def __init__(self, symbol):
self.symbol = symbol
def print_discrep(self):
print('This is a test function for the graph ' + self.symbol)
它在我的模板中返回None。
您正在視圖中調用該函數。 要在模板中調用它,請分配函數對象,而不是函數調用的結果:
test = earnings_object.print_discrep # no ()
更新:將print
打印到命令行,而不是模板。
該模板顯示您調用的函數的返回值。 您的print_discrep
沒有返回值,默認為None
。
如果要在模板中顯示數據,請在函數中返回該數據:
def get_discrep(self):
return 'This is a test function for the graph ' + self.symbol
然后,您可以在視圖或模板中調用該函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.