treyhunner

urlman metaclass hack

Feb 5th, 2020
426
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. """
  2. If the code in the urlman docs is run with the below Urls class:
  3.  
  4. .. code-block:: python
  5.  
  6.    class Group(models.Model):
  7.  
  8.        ...
  9.  
  10.        class urls(Urls):
  11.            view = "/{self.slug}/"
  12.            users = "{view}users/"
  13.            admin = "{view}admin/"
  14.  
  15. This model will also have a ``get_absolute_url`` method also:
  16.  
  17. .. code-block:: pycon
  18.  
  19.    >>> group = Group(slug="hello")
  20.    >>> group.get_absolute_url()
  21.    '/hello/'
  22.    >>>> group.urls.view
  23.    '/hello/'
  24. """
  25.  
  26. import urlman
  27.  
  28.  
  29. class UrlsMeta(urlman.UrlsMetaclass):
  30.     def __set_name__(self, cls, name, **kwargs):
  31.         urls = self.urls
  32.         def get_absolute_url(self):
  33.             return self.urls.view
  34.         if not hasattr(cls, 'get_absolute_url') and 'view' in urls:
  35.             setattr(cls, 'get_absolute_url', get_absolute_url)
  36.  
  37.  
  38. class Urls(urlman.Urls, metaclass=UrlsMeta):
  39.     """
  40.    urlman.Urls that adds a get_absolute_url method automatically
  41.    """
Add Comment
Please, Sign In to add comment