Django:如何使用其他.py文件中定义的变量?



我想在另一个文件 plots.py 的函数 get_price(( 中使用下面的 x 作为变量。

views.py

class ScatterView(TemplateView) :
def get(self, request, *args, **kwargs) :
context = super().get_context_data(**kwargs)
context['form'] = SampleForm() 
x = request.GET.get('x')
context['calculated_x'] = plots.get_price()
return render(request, 'index.html', context)

plot.py

def get_price():
input_x = x + 1
return input_x

但它不起作用。 我该如何描述用于此目的的功能? 关键是,我需要稍后通过 views.py 使用模板的返回值。

为什么不直接通过它呢?将代码更改为如下所示的内容:

def get_price(x):
input_x = x + 1
return input_x

像这样将其导入类:

import plots

将其添加到您的代码中,如下所示:

class ScatterView(TemplateView) :
def get(self, request, *args, **kwargs) :
context = super().get_context_data(**kwargs)
context['form'] = SampleForm() 
x = request.GET.get('x')
context['calculated_x'] = plots.get_price(x)
return render(request, 'index.html', context)

你需要在 plot.py 中将x传递给get_price(x(

views.py

import plot.ply as plots
class ScatterView(TemplateView) :
def get(self, request, *args, **kwargs) :
context = super().get_context_data(**kwargs)
context['form'] = SampleForm() 
x = request.GET.get('x')
context['calculated_x'] = plots.get_price(x)
return render(request, 'index.html', context)

plot.py

def get_price(x):
input_x = x + 1
return input_x

最新更新