【问题标题】:Django: How can I use variable defined in the other .py file?Django:如何使用在另一个 .py 文件中定义的变量?
【发布时间】:2019-09-26 18:19:33
【问题描述】:

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

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使用模板的返回值。

【问题讨论】:

  • 您需要将x 变量传递给get_price(x) 函数并对其进行处理。

标签: python django function view arguments


【解决方案1】:

为什么不直接通过呢?把你的代码改成这样:

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)

【讨论】:

  • 谢谢两位,我试过了,但出现如下错误代码
  • ValueError at /simulator/ 输入包含 NaN、无穷大或对于 dtype('float64') 来说太大的值。请求方法:GET 请求 URL:127.0.0.1:8000/simulator Django 版本:2.2.4 异常类型:ValueError 异常值:输入包含 NaN、无穷大或对于 dtype('float64') 太大的值。
  • 其实我用 sklearn 在 get_price() 做了一些机器学习计算
  • 异常位置:/Users/user/.pyenv/versions/3.7.3/lib/python3.7/site-packages/sklearn/utils/validation.py in _assert_all_finite,第 56 行 Python 可执行文件: /Users/user/.pyenv/versions/3.7.3/bin/python3 Python 版本:3.7.3 Python 路径:['/Users/user/Desktop/Django/price_simulator', '/Users/user/.pyenv/versions /3.7.3/lib/python37.zip', '/Users/user/.pyenv/versions/3.7.3/lib/python3.7', '/Users/user/.pyenv/versions/3.7.3/lib /python3.7/lib-dynload', '/Users/user/.pyenv/versions/3.7.3/lib/python3.7/site-packages', '/Users/user/.pyenv/versions/3.7.3 /lib/python3.7/site-
  • 当我给定值时,没有问题,模板出现了。如果没有值,由于我的计算出错,它似乎无法正确显示模板?
【解决方案2】:

您需要在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2011-02-19
    • 2021-08-05
    • 1970-01-01
    • 2016-12-21
    • 2021-10-29
    相关资源
    最近更新 更多