0

From a database I have a text, which must dynamically load a class of my views.

The example as I have at the moment is:

-projectname
    -appname
        -views.py
        -templates
            -appname
                -index.html

in views.py

class SelectCampaign(View):

    def get(self, request, *args, **kwargs):

        campaign = Campaign.objects.values('campaign_name').filter(user=request.user)[0]

        #this is where I need you to automatically load with varying campaign
        generic_class = MyClassCampaignName1() 
        #example: generic_class = class called MyClassCampaignName1

        return generic_class.render_index(request)

class MyClassCampaignName1():

    def render_index(self, request, *args, **kwargs):
        return render(request, 'appname/index.html', {}, context_instance=RequestContext(request))

The name that brings the database to dynamically load a class with the same name

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • I don't think this is django specific. If it isn't, take a look at https://stackoverflow.com/questions/1176136/convert-string-to-python-class-object – spalac24 Sep 04 '15 at 21:03

1 Answers1

0

Here are a couple ways to get objects from their string name. I like getattr the most.

# outside.py
class OuterDummy():
    def __init__(self):
        print 'This is outer Dummy!'

# main.py
class InnerDummy():
    def __init__(self):
        print 'This is inner Dummy!'

if __name__ == "__main__":
    # Method 1) Use the globals object
    class_1 = globals().get('InnerDummy')
    instance_1 = class_1()
    # stdout: This is inner Dummy!

    # Method 2) Use getattr
    import outside
    class_2 = getattr(outside, 'OuterDummy')
    instance_2 = class_2()
    # stdout: This is outer Dummy!

python main.py

pztrick
  • 3,741
  • 30
  • 35