42

Is there a way to print the current URL in Jinja2/Flask?

E.g. if the current URL is http://www.domain.com/example/1/2

{{ request.path }} works and prints /example/1/2, but how to I get the full URL with http:// as well?

From the docs (here){{ request.url }} should work, but it doesn't yield anything.

Thanks

UPDATE

Here are the render/context args from views.py:

class EventDetailView(EventObjectMixin, FormView):
    template_name = 'gig/public/about.html'
    context_object_name = 'event'
    form_class = EventPurchaseTicketForm

    def get_context_data(self, **kwargs):
        context = super(EventDetailView, self).get_context_data(**kwargs)

    ...

        return context
alias51
  • 8,178
  • 22
  • 94
  • 166
  • 4
    Does `{{request.path}}` actually work **in your template?** You might simply be missing `request` in your context. Please show us the code that calls the Jinja template's render method (or at least the code that generates the context for it). – Thomas Orozco Oct 09 '14 at 11:01
  • Yes, it works. I am editing someone else's code - where is the render method usually found? In models.py? – alias51 Oct 09 '14 at 11:06
  • 1
    More likely in the view code (the request handler with the logic for that URL) – Thomas Orozco Oct 09 '14 at 11:06
  • Ok, thanks, what would the typical function/argument be that I'm looking for? – alias51 Oct 09 '14 at 11:10
  • Anything that says `render`, `render_template`, or `context` is likely. – Thomas Orozco Oct 09 '14 at 11:15
  • Unfortunately this isn't really helpful. We'd need to see the code for the original `get_context_data` method, as well as where that context is used. – Thomas Orozco Oct 09 '14 at 12:40

3 Answers3

38

You can use {{ url_for(request.endpoint) }}, it works.

hugoxia
  • 428
  • 4
  • 2
  • 9
    Note that you get an error if the route associated with `request.endpoint` requires a few parameters. This [answer to a similar question](https://stackoverflow.com/a/25013141/4453460) provides a better idea. – lfurini Mar 11 '19 at 14:32
26

For folks who have routes that require additional arguments, the accepted answer won't quite work, as mentioned by @lfurini.

The following will use the view's arguments when constructing the URL:

{{ url_for(request.endpoint, **request.view_args) }}
Kirkman14
  • 1,506
  • 4
  • 16
  • 30
3

Find where you have similar code to this, usually found in controller.py or __ init__.py or views.py :

from flask import render_template
...

@app.route('/example/<arg1>/<arg2>')
def some_view_function(arg1, arg2):
    ...

    return render_template('path/to/your/template.html')

With render_template() are request and other variables available to you.

gcerar
  • 920
  • 1
  • 13
  • 24