Encoding URL query parameters in Javascript + Django
When passing arbitrary strings as parameters for some function, you may be tempted to do it using a path component, which can be decoded easily with Django.
Do not do it. Forward slashes will be encoded in arbitrary ways (and you should note that the “string” path component in Django excludes forward slashes). Use query parameters instead, as follows.
In Javascript:
searchParams = new URLSearchParams({'parameter': 'value'});
URLparams = searchParams.toString();
// use this string to build your URL
URL = "http://<server>/endpoint" + URLparams;
In Django:
# url
path('endpoint', views.endpoints.endpoint_function),
# view function in endpoint
def endpoint_function(request):
parameter = request.query_params.get('parameter', DEFAULT_VALUE)
This will ensure correct encoding and decoding of parameters.