簡體   English   中英

如何將Django模型字段傳遞給函數並讓變量返回上下文以在模板中使用

[英]How to pass django model field to function and have variables returned to context for use in template

我有一些以表格形式從用戶那里收集的值,這些值已保存到數據庫中。 我想獲取這些值,在函數中對它們執行操作,然后返回它們,以便可以與其他上下文一起在它們中使用它們。

這是我的模型:

#models.py file
class MyModel(models.Model):
    varA = models.PositiveIntegerField()
    varB = models.PositiveIntegerField()
    varC = models.PositiveIntegerField()

這是我正在使用的外部函數:

#makecalc.py
def MakeCalc(varA, varB, varC):
    #simplified from what I am actually doing
    varD = varA*varB**varC 
    varE = varA+varB+varC
    return varD, varE

這是views.py文件:

#views.py file
from .makecalcs import MakeCalc
class MySummary(DetailView):
    model = MyModel

    def get_vars(self):
        varD, varE = MakeCalc(varA, varB, varC) #Am I passing this correctly?
        return varD, varE #How do I send these to context?

最后是html:

<p> you input: {{ MyModel.varA }}</p>
<p> you input:{{ MyModel.varB }}</p>
<p> you input:{{ MyModel.varC }}</p>
<p> I output:{{ varD }}</p> #how do I call this?
<p> you input:{{ varE }}</p> #how do I call this?

因此,我的問題是在視圖中,如何將varD,varE添加到上下文中,以便可以與模型中的varA,varB和varC一起使用?

get_context_data()方法添加到視圖中,如下所示:

def get_context_data(self, **kwargs):
    context = {}
    context['your_custom_var'] = 'your_custom_value'
    return super(MySummary, self).get_context_data(**context)

暫無
暫無

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

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