如何在django中使用视图中的模型函数?
假设我在模型中定义了一个函数来返回格式化值,如:如何在django中使用视图中的模型函数?,django,Django,假设我在模型中定义了一个函数来返回格式化值,如: def formatMoney(self): return '$' + self.money 我如何在我的视图中使用此选项 我想我表达得不好。我试图在模板文件中而不是视图类中使用它,因为我在模板文件中进行迭代。从模型实例调用函数,就像在视图外的实例上调用函数一样 # views.py def your_view(request): instance = YourModel.objects.get(pk=234) insta
def formatMoney(self):
return '$' + self.money
我如何在我的视图中使用此选项
我想我表达得不好。我试图在模板文件中而不是视图类中使用它,因为我在模板文件中进行迭代。从模型实例调用函数,就像在视图外的实例上调用函数一样
# views.py
def your_view(request):
instance = YourModel.objects.get(pk=234)
instance.formatMoney()
render(request, 'your_template.html', {'instance': instance})
# your_template.html
{{ instance.formatMoney }}
若要在djangos模板语言内部调用方法,请省略从模型实例调用函数的
()
,方法与在视图外部的实例上调用函数相同
# views.py
def your_view(request):
instance = YourModel.objects.get(pk=234)
instance.formatMoney()
render(request, 'your_template.html', {'instance': instance})
# your_template.html
{{ instance.formatMoney }}
若要在djangos模板语言内部调用方法,请省略从模型实例调用函数的
()
,方法与在视图外部的实例上调用函数相同
# views.py
def your_view(request):
instance = YourModel.objects.get(pk=234)
instance.formatMoney()
render(request, 'your_template.html', {'instance': instance})
# your_template.html
{{ instance.formatMoney }}
若要在djangos模板语言内部调用方法,请省略从模型实例调用函数的
()
,方法与在视图外部的实例上调用函数相同
# views.py
def your_view(request):
instance = YourModel.objects.get(pk=234)
instance.formatMoney()
render(request, 'your_template.html', {'instance': instance})
# your_template.html
{{ instance.formatMoney }}
要调用djangos模板语言内部的方法,请省略
()
对不起,我在问题中添加了更多信息,现在我搜索了模板而不是视图,我找到了答案,谢谢。对不起,我在问题中添加了更多信息,现在我搜索了模板而不是视图,我找到了答案,谢谢。对不起,我在问题中添加了更多信息,现在我搜索了模板而不是视图,我找到了答案,谢谢。对不起,我在问题中添加了更多信息,现在我搜索了模板而不是视图,我找到了答案,谢谢。