Skip to content

Instantly share code, notes, and snippets.

@pawnhearts
Last active April 15, 2025 11:50
Show Gist options
  • Save pawnhearts/94ea6149aa7a27b2b72b1586949fa9df to your computer and use it in GitHub Desktop.
Save pawnhearts/94ea6149aa7a27b2b72b1586949fa9df to your computer and use it in GitHub Desktop.
import re
from pathlib import Path
from django.urls import path
from django.views import View
from parts.templatetags.url_replace import url_replace
def walk_views(cls=View):
for subcls in cls.__subclasses__():
if hasattr(cls, '__subclasses__'):
yield from walk_views(subcls)
yield subcls
def walk_our_views():
for cls in walk_views():
module = __import__(cls.__module__)
if Path(module.__file__).absolute().parent.parent == Path('.').absolute().parent:
yield cls
def mk_path(cls):
url_path = getattr(cls, 'url_path', None)
name = getattr(cls, 'url_name', None)
if url_path is None:
url_path = re.sub(r'(?<!^)(?=[A-Z])', '_', cls.__name__.replace('View', '')).lower()
if not url_path.endswith('/'):
url_path += '/'
if pk := getattr(cls, 'pk_url_kwarg'):
url_path += f'<int:{pk}>/'
if name is None:
name = url_path.replace('_', '-'.strip('/'))
return path(url_path, cls.as_view(), name=name)
def generate_url_patterns():
url_patterns = []
for cls in walk_our_views():
url_patterns.append(mk_path(cls))
return url_patterns
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment