passing request in django template tag

6.2k views Asked by At

I tried to access the request in my custom template tag function. But it is not working.

views.py

def candidate(request):
   .......
   .......
   return render(request, template, context)

templatetags

@register.simple_tag(takes_context=True)
def make_url(context, doc_url):
    request = context["request"]
    protocol = "https://" if request.is_secure() else "http://"
    host = request.get_host()
    new_url = "%s%s%s" %(protocol, host, doc_url)
    return new_url

template.html

<iframe src="{{  candidate.resume_file.url | make_url }}" frameborder="0"></iframe>
1

There are 1 answers

0
Shiva Krishna Bavandla On BEST ANSWER

Django filters aren't given any special access to the context from which they are called, they're just plain old functions.

You'll need to pass in anything you want to use within the function.

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

source : Can custom Django filters access request.user?