简体   繁体   English

如何在Views.py中运行函数并打印结果? — Django

[英]How Can I Run a Function Inside of Views.py and Print Result? — Django

The problem is that I am trying to call a function from my views.py and print the result in my template through a context variable. 问题是我试图从views.py调用一个函数,并通过上下文变量将结果打印到模板中。 The function prints in the terminal and does not work in the template. 该功能在终端上打印,在模板中不起作用。 I posted a question a few days ago regarding doing this with subprocess, but I still could not figure it out. 几天前,我发布了一个关于使用子流程执行此操作的问题,但我仍然无法弄清楚。

How can I print "This is a test function for AAPL" in my template instead of in the terminal? 如何在模板而不是终端中打印“这是AAPL的测试功能”?

Views.py 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 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)

It is returning None in my template. 它在我的模板中返回None。

You're calling the function in the view. 您正在视图中调用该函数。 To call it in the template, assign the function object, not the result of the function call: 要在模板中调用它,请分配函数对象,而不是函数调用的结果:

test = earnings_object.print_discrep  # no ()

Update: print prints to the command line, not into your template. 更新:将print打印到命令行,而不是模板。

The template displays the return value of functions you call. 该模板显示您调用的函数的返回值。 Your print_discrep doesn't have a return value, defaulting to None . 您的print_discrep没有返回值,默认为None

If you want to display data in the template, return that data in your function: 如果要在模板中显示数据,请在函数中返回该数据:

def get_discrep(self):
    return 'This is a test function for the graph ' + self.symbol

Then you can call the function either in the view or in the template. 然后,您可以在视图或模板中调用该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM