Skip to content
Advertisement

Send query params from Jinja template

I can’t figure out if it’s possible to pass query parameters from a static html page to a view for processing. I have now implemented the functionality I need using path parameters. I want to do the same, but with query parameters

main.py

JavaScript

events.py

JavaScript

routes.py

JavaScript

html

JavaScript

It’s works with "POST /event/invite/15/sender/3 HTTP/1.1" as a sample

Try with query params

JavaScript

And get

JavaScript

html template without any change

Can I pass query parameters from the template to the fastapi logic to processing this url /event/?event_invite=15&sender=3?

Advertisement

Answer

This is Starlette’s issue (i.e., url_for() receives path parameters, not query parameters). What you could do is to create a custom URL processor (as shown below) and use it to pass path and/or query parameters as well.

JavaScript

Remember to add the CustomURLProcessor class to the templates’ global environment:

JavaScript

Then, use in Jinja template, as below:

JavaScript

Please have a look at this answer for a complete working example. Also, this feature might be introduced into the next version of Starlette #1385. Thus, you may want to keep an eye on it.

More options on how to make a class accessible from Jinja templates

Alternative options to make CustomURLProcessor class accessible from Jinja templates, in case templates.env.globals['CustomURLProcessor'] = CustomURLProcessor didn’t work for you, throwing the following error: jinja2.exceptions.UndefinedError: 'CustomURLProcessor' is undefined.

Option 1

JavaScript

Option 2

JavaScript

You could even add the whole module, and use in Jinja template like this helpers.CustomURLProcessor().url_for(request....

JavaScript

Option 3

The last option would be to pass it as part of your TemplateResponse.

JavaScript

If none of the above worked, perhaps other options described here might help, or the problem likely lies elsewhere.

Update – About including query params

Regarding sending query parameters from a Jinja template, you can now use Starlette’s starlette.datastructures.URL, which provides an include_query_params method.

To use, import the URL class and make it accessible from Jinja2 templates:

JavaScript

Then, use in Jinja template as shown below:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement