簡體   English   中英

Django:如何使用 other.py 文件中定義的變量?

[英]Django: How can I use variable defined in the other .py file?

我想在另一個文件 plots.py 中使用下面的 x 作為 function get_price() 中的變量。

視圖.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

但它不起作用。 為此,我該如何描述 function? 關鍵是,我需要稍后通過views.py 使用模板的返回值。

為什么不直接通過呢? 將您的代碼更改為以下內容:

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

像這樣將它導入到 class 中:

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)

視圖.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM