Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Get generic view class from url name

Tags:

django

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.

like image 281
Pickels Avatar asked Apr 21 '11 19:04

Pickels


2 Answers

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
like image 127
fmoor Avatar answered Sep 19 '22 04:09

fmoor


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.

like image 20
Pickels Avatar answered Sep 21 '22 04:09

Pickels