Home > Net >  Retrieving ID atribute from URL
Retrieving ID atribute from URL

Time:08-25

In my django project i have a url:

https://example.com/nice_page#123

This url will lead user to particular post on my page, this is an example how it works on stackoverflow:

What is the "N 1 selects problem" in ORM (Object-Relational Mapping)? (it is a link to particular answer, and your browser will move you right to this answer.)

My goal is to get this #123 id from url.

I can't do it with django's META data by request.META it doesn't show this #123 id, it only returns me https://example.com/nice_page

How can i get this #123 id? I would prefer making it with django, but javascript is also acceptable.

Update: as follows from the comments, thanks to – Willem Van Onsem and Ankit Tiwari, this task is unsolvable by server-side (by django) How to access url hash/fragment from a Django Request object

CodePudding user response:

Yes, only with JavaScript. E.g. using an example from here:

const url = new URL('https://example.com/nice_page#123');
console.log(url.hash); // Logs: '#123'

Or reference the hash of the current URL in a browser:

console.log(window.location.hash);

CodePudding user response:

You could use location.search and URLSearchParams.

https://example.com/nice_page?id=123

const params = new URLSearchParams(window.location.search);
const id = parseInt(params.get("id"));
console.log(id);

You can read more about here: https://developer.mozilla.org/en-US/docs/Web/API/Location/search

  • Related