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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With