encodeURIComponent is not honouring forwards slashes

I have my url as follows :

path('azure/pricing/instance/<instance_id>/<location>', views.get_azure_instance_pricing, name='azure_instance_pricing'),

And in JavaScript :

instance = encodeURIComponent(instance);
location = encodeURIComponent(location);
const URL = `${BASE_URL}api/azure/pricing/instance/${instance}/${location}`;
return fetch(URL);

But Django returns 404 when an instance in the JavaScript is like D14/DS14 Spot

Even though I’ve given encodeURIComponent(instance) when fetching, its trying with an additional slash - the one in-between D14 and DS14:


Django 4.2.5

Check the value of URL after that third line. If the slash is not url-encoded, check to make sure you’re not doing something like trying to reassign a value to a const or something like that.

It might be worthwhile to just try assigning those encoded values to new variables. You may also want to check the browser console for any error messages.

(This is a JavaScript issue and not a Django issue.)

Hi. I think that whether or not slash is urlencoded in url won’t change anything as django decodes url before doing resolution : this was discussed in this ticket (#15718 (Django unquotes urls and not able to distinguish %2F and /) – Django).

So, the problem here is that the <instance_id> part of the url must be declared with path type (<path:instance_id>), so that url can resolve

Unfortunately if location can also contain slashes, then django won’t be able to correctly split between the instance_id and location because it won’t know on which slash to split

So I have to replace the slash with another non-common character in JavaScript and check for the same in python (and replace the non-common character in the URL with the slash) ?

There are several workarounds depending on how exactly the instance_id and location are formatted.

If location cannot contain slashes, you’re good with only defining <path:instance> in the url.

If location can contain slashes, and you have a character (or sequence of characetrs) which cannot occur in instance_id and/or location (e.g. _ is forbidden), you can use it as a separator in the url: .../<path:instance_id>/_/<path:location>.

If instance and/or location satisfy a specific pattern (e.g. there is always one and only one slash in instance_id) you can define the url using an re_path (django.urls functions for use in URLconfs | Django documentation | Django).