How to get current URL in jinja2/flask (request.url not working)

Question:

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
Asked By: alias51

||

Answers:

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.

Answered By: gcerar

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

Answered By: hugoxia

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) }}
Answered By: Kirkman14
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.