![](/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.