Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How may I resolve python path strings with Django?

Tags:

python

django

I'm currently writing a Django template template tag, and I would like to be able to reference a class in it with a string, just like in settings.MIDDLEWARE_CLASSES, for example. The tag would look like {% mytag "myproject.lib.mymodule.SomeClass" %}.

The question is fairly simple : in my template tag, how may I easily resolve this string to the actual referenced class?

Thanks.

like image 802
Pierre Avatar asked Apr 23 '26 12:04

Pierre


1 Answers

If you really need to import a package specified as a string, you will need to check out the __import__ function.

Basic usage is that you can attempt to import the package specified in the string like

my_class = __import__("myproject.lib.mymodule.SomeClass")

which is equivalent to

import myproject.lib.mymodule.SomeClass as my_class

However, as S.Lott mentioned, you'll need to consider carefully if that's really the best way to solve the problem.

like image 77
Michael C. O'Connor Avatar answered Apr 26 '26 03:04

Michael C. O'Connor