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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.