如何根据Django的URL路径获取对应的类视图(Class-based View)类本身
Retrieve Class-Based View from URL Path in Django
Absolutely! You can retrieve the original class-based view (CBV) associated with a URL path like hello/foo/ in Django—here's a straightforward implementation that gets you the actual class (not just the view function returned by as_view()):
Step-by-Step Solution
1. Use Django's resolve() Function
Django's resolve() function parses a URL path and returns a ResolverMatch object, which contains details about the matched URL pattern and its associated view.
2. Access the view_class Attribute
When you use a CBV with as_view(), the returned view function has a special view_class attribute that points directly to the original class. This is a built-in Django convention for tracking the source CBV.
Implementation Code
from django.urls import resolve def get_view_class_from_path(the_url): try: # Resolve the URL path to get the match details match = resolve(the_url) # Check if the matched view is a CBV's as_view() result if hasattr(match.func, 'view_class'): return match.func.view_class else: # Return None or raise an error if it's a function-based view return None except Exception as e: # Handle cases where the URL doesn't match any pattern print(f"Failed to resolve URL: {str(e)}") return None
Test It Out
Using your example URL pattern:
the_url = "hello/foo/" url_associated_view = get_view_class_from_path(the_url) # Print the full class reference print(url_associated_view) # Output: <class 'your_app.views.HelloView'> # Print just the class name (as you requested) print(url_associated_view.__name__) # Output: HelloView
Key Notes
- Ensure the URL path you pass is relative to your project's root URLconf (include any prefixes if your app is mounted under a path like
/api/). - If the URL matches a function-based view instead of a CBV, the function will return
None(you can adjust this to raise an exception if needed). - The
view_classattribute is a stable part of Django's CBV implementation, so this approach is safe to use across supported Django versions.
内容的提问来源于stack exchange,提问作者Benjamin_Mourgues
相关产品推荐
相关产品推荐

