Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - pass parameter from template to models.py' s function

I' ve a model called mymodel, which has a property getp, but this requires a parameter (request):

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.

Any workaround for this problem?

Thanks.

like image 434
user2194805 Avatar asked Aug 25 '26 08:08

user2194805


1 Answers

seems a duplicate of How to use method parameters in a Django template?

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 %}
like image 128
fsw Avatar answered Aug 27 '26 00:08

fsw