Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I get a slug from a url?
#1
How do I get a slug from a url?
Example:... com/page1/
In my case - page1 is a slug and I want to get it in a template for different operations
Reply
#2
Can eg use urlparse.
>>> from urllib.parse import urlparse
>>> 
>>> url = 'https://example.com/page1/'
>>> u = urlparse(url)
>>> u
ParseResult(scheme='https', netloc='example.com', path='/page1/', params='', query='', fragment='')
>>> u.path
'/page1/'
>>> 
>>> url = "https://www.allrecipes.com/recipe/79300/real-poutine?search=random/some-name/"
>>> u = urlparse(url)
>>> u
ParseResult(scheme='https', netloc='www.allrecipes.com', path='/recipe/79300/real-poutine', params='', query='search=random/some-name/', fragment='')
>>> u.path
'/recipe/79300/real-poutine'
>>> u.query
'search=random/some-name/'
Reply
#3
Thanks!!!
Reply
#4
(Apr-21-2023, 11:28 AM)snippsat Wrote: Can eg use urlparse.
[python]>>> from urllib.parse import urlparse
>>>
.............

How do I embed this code in tempates?
I have a menu with links on my site. I create links using get_absolute_url
When I follow the link, I call the view with the desired template. In this template, I need to find out: where I came from (i.e. slug!) (by slug I will find the menu item, menu parent and assign the necessary classes in the desired place of the menu)

Probably i can just pass to view everything that I need to disassemble in the template???
But I had not yet studied this moment. If this is more correct, then I will go this way.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020