#19005 closed New feature (wontfix)
Allow class based views to be included in urls.py by name as a string
Reported by: | Tim Anderegg | Owned by: | nobody |
---|---|---|---|
Component: | Core (URLs) | Version: | dev |
Severity: | Normal | Keywords: | cbv |
Cc: | timothy.anderegg@… | Triage Stage: | Unreviewed |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
Class based views currently have to be imported into urls.py and then added to urlpatterns using ClassBasedView.as_view().
It would be relatively trivial, it seems, to add functionality to the method 'get_callable' in django.core.urlresolvers that uses inspect.isclass to determine if the lookup_view refers to a class, and if so set lookup_view = lookup_view.as_view(), throwing an exception if lookup_view is a class but the method as_view() doesn't exist.
This would help cleanup urls.py when using class based views, and be more consistent with how function based views are handled. Is there any reason not to do this? If people support this I will submit a patch.
Change History (5)
comment:1 by , 12 years ago
Cc: | added |
---|---|
Version: | 1.4 → master |
comment:3 by , 12 years ago
Resolution: | → wontfix |
---|---|
Status: | new → closed |
I'm wontfixing this. It was an intentional design decision for CBVs not to have any special support in the URL system or elsewhere. Making this change would complicate the view contract, which ATM is very simple.
For bonus points I'll add that I consider the string import path thing in urls to be an anti-pattern and whose use should be discouraged.
comment:4 by , 12 years ago
Fair enough, maybe I should just abandon string import paths in general then. Thanks all,
Tim
comment:5 by , 12 years ago
One last note: you can use the following pattern:
class MyClassBasedView(View): # ... my_class_based_view = MyClassBasedView.as_view()
and then refer to my_class_based_view
by name in the URLconf. Granted, it's one line of boilerplate.
Importing views by name in URLconfs has a big drawback: import errors are delayed until runtime. Resulting tracebacks can be confusing. I'd prefer to move away from identifying views by name. Hence I'm -0 on this proposal.
I also have a backwards compatibility nitpick. Technically, a view can be any callable, including a class. The following class is a valid Django view:
I don't know if this pattern is common or even useful, but it's something that currently works, and your proposal would break it.