6

What's the recommended way of getting a generic view class from the url name?

url(r'^$', HomeView.as_view(), name='home')

So with 'home' I want to get the class HomeView.

Pickels
  • 33,902
  • 26
  • 118
  • 178
  • You might want to go the other way round: from the view class' name to the url name. Why? Because class names are the more highly structured world. For instance, after a typo you will get a more meaningful error message if the offending line contains a name that does not resolve right there. (For class-based views, you would make a helper that applies `.as_view()` for you to make both the resolving and the notation simpler.) – Lutz Prechelt Nov 14 '14 at 13:59

3 Answers3

11

Django 1.9 introduced 2 attributes to the functions that as_view() returns. view_initkwargs and view_class.

Combining this with Pickles' answer:

from django.urls import reverse, resolve

url = reverse('home')
view = resolve(url).func.view_class
fmoor
  • 349
  • 2
  • 8
7

The get_class I got from the following question: Does python have an equivalent to Java Class.forName()?

url = reverse('home')
resolver_match = resolve(url)
func = resolver_match.func
module = func.__module__
view_name = func.__name__

clss = get_class( '{0}.{1}'.format( module, view_name ) )

This is what I came up with myself I am very open to other answers.

Community
  • 1
  • 1
Pickels
  • 33,902
  • 26
  • 118
  • 178
  • 1
    I haven't found something better, but it's not completly satisfying because it is not exactly *fetching a view from its name*. The name is not enough to perform a call to `reverse` when the said url needs extra parameters (id for instance). – challet Dec 03 '20 at 14:19
6

Inspired by Pickels' answer:

import importlib 
from django.core.urlresolvers import reverse, resolve

view_name = 'my_view_name'

view_func = resolve(reverse(view_name)).func
module = importlib.import_module(view_func.__module__)
view = getattr(module, view_func.__name__)
seddonym
  • 16,304
  • 6
  • 66
  • 71