0

So I'm trying to load a model dynamically as such :

urls.py

url(r'^list_view/([\w-]+)$', Generic_list.as_view()),

Here's my Generic_list class in views.py :

class Generic_list(ListView):
    import importlib
    module_name = 'models'
    class_name = ?
    module = __import__(module_name, globals(), locals(), class_name)
    model = getattr(module, class_name)
    template_name = 'django_test/generic_list.html'

About security, later I'll only allow classes from a white list.

So, what can I put in place of the question mark in order to get the class name from the url?

Loic
  • 90
  • 6
  • Hi there, have a look at this http://ccbv.co.uk/projects/Django/1.8/django.views.generic.list/ListView/ – Paco Jul 17 '15 at 11:05

2 Answers2

1

If you want to have your model loaded dynamically, you could do something like this:

class Generic_list(ListView):
    template_name = 'django_test/generic_list.html'

    @property
    def model(self):
        return # code that returns the actual model

More information about property. Basically, it will understand this method as an attribute of the class. Instead of having to define this attribute at the class level (meaning that the code will be evaluated when the file is imported by django), you make it look like it is an attribute, but it's acting like a method, allowing you to add business logic.

Community
  • 1
  • 1
Paco
  • 4,520
  • 3
  • 29
  • 53
1

You could try to use property decorator and get_model method:

from django.views.generic import ListView
from django.apps import apps


class GenericList(ListView):

    @property
    def model(self):
        # Obtain model name here and pass it to `get_model` below.
        return apps.get_model(app_label='app_label', model_name='model_name')

Also, consider reading PEP 0008 for naming conventions.

Ernest
  • 2,799
  • 12
  • 28