I' ve a model called mymodel, which has a property getp, but this requires a parameter (request):
我有一个名为mymodel的模型,它有一个属性getp,但这需要一个参数(请求):
class Mymodel(models.Model):
...
def getp(self, request):
return "STH"
. From the views i pass the request and one model to the template:
。从视图中,我将请求和一个模型传递给模板:
return render_to_response('x.html', {
'mymodel': Mymodel.objects.get(id=17),
'request': request
}, context_instance = RequestContext(request))
, and from the template file is there any way to call the getp function with the request parameter? I know this shouldn' t be used like this, but my question is rather theoretical than practical.
,从模板文件中是否有方法使用请求参数调用getp函数?我知道这不应该这样使用,但我的问题是理论性的,而不是实践性的。
Any workaround for this problem?
有办法解决这个问题吗?
Thanks.
谢谢。
1 个解决方案
#1
2
seems a duplicate of How to use method parameters in a Django template?
如何在Django模板中使用方法参数?
one solution would be to pass result of your method to template. something like:
一种解决方案是将方法的结果传递给模板。喜欢的东西:
object = Mymodel.objects.get(id=17)
return render_to_response('x.html', {
'mymodel': object,
'mymodel_getp': object.getp(request),
'request': request
}, context_instance = RequestContext(request))
other solution would be to write a custom template tag:
其他解决方案是编写自定义模板标记:
@register.simple_tag(name="model_getp", takes_context=True)
def model_getp(context, object=None):
return object.getp(context)
and then in template:
然后在模板:
{% model_getp mymodel %}
#1
2
seems a duplicate of How to use method parameters in a Django template?
如何在Django模板中使用方法参数?
one solution would be to pass result of your method to template. something like:
一种解决方案是将方法的结果传递给模板。喜欢的东西:
object = Mymodel.objects.get(id=17)
return render_to_response('x.html', {
'mymodel': object,
'mymodel_getp': object.getp(request),
'request': request
}, context_instance = RequestContext(request))
other solution would be to write a custom template tag:
其他解决方案是编写自定义模板标记:
@register.simple_tag(name="model_getp", takes_context=True)
def model_getp(context, object=None):
return object.getp(context)
and then in template:
然后在模板:
{% model_getp mymodel %}