Skip to content

Instantly share code, notes, and snippets.

@corentinbettiol
Last active August 9, 2022 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save corentinbettiol/844f29c93538576ba40ec95762e26ce9 to your computer and use it in GitHub Desktop.
Save corentinbettiol/844f29c93538576ba40ec95762e26ce9 to your computer and use it in GitHub Desktop.
Get a djangocms Page object from a slug, without having to launch all the stuff behind djangocms.

Here's a small gist allowing you to find a Page (the DjangoCMS object) from a slug:

def get_page(self, page_url):
    """Try to find a cms page with the same slug, and returns the id of its public page."""
    potential_pages = Page.objects.filter(title_set__slug=page_url.split("/")[-2])  # get "dede" in "https://aa.aa/aa/aa/aa/dede/"
    for page in potential_pages:
        if page.get_absolute_url() == page_url.replace(domain_name, "") and page.publisher_is_draft == False:
            return page
    breakpoint()

You must have a domain_name str available (or you can add it as an argument in the function and pass it).

Example:

>>> def get_page(self, page_url):
...     """Try to find a cms page with the same slug, and returns the id of its public page."""
...     potential_pages = Page.objects.filter(title_set__slug=page_url.split("/")[-2])  # get "dede" in "https://aa.aa/aa/aa/aa/dede/"
...     for page in potential_pages:
...         if page.get_absolute_url() == page_url.replace(domain_name, "") and page.publisher_is_draft == False:
...             return page
...     breakpoint()
... 
>>> 
>>> domain_name = "http://localhost:8000"
>>> url = http://localhost:8000/en/things-to-do/hiking/requirements/
>>> page = get_page(url)
>>> page
<cms.models.pagemodel.Page id=404 is_draft=False object at 0x00deadbeef00>
>>> page.get_absolute_url()
'/en/things-to-do/hiking/requirements/'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment