Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在django中使用视图中的模型函数?_Django - Fatal编程技术网

如何在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模板语言内部的方法,请省略
()

对不起,我在问题中添加了更多信息,现在我搜索了模板而不是视图,我找到了答案,谢谢。对不起,我在问题中添加了更多信息,现在我搜索了模板而不是视图,我找到了答案,谢谢。对不起,我在问题中添加了更多信息,现在我搜索了模板而不是视图,我找到了答案,谢谢。对不起,我在问题中添加了更多信息,现在我搜索了模板而不是视图,我找到了答案,谢谢。