Great! Thanks a lot, it worked!

Here's a little function that I made and that is quite helpful:

def get_class(class_path):
    i = class_path.rfind('.')
    module_path, class_name = class_path[:i], class_path[i+1:]
    module = __import__(module_path, globals(), locals(),
[class_name])
    return getattr(module, class_name)

Thanks again for your help. That wasn't easy, but that made me visit
some parts of Python and Django that I didn't know about. And it does
demystify a lot of things!

On Feb 13, 1:40 pm, Malcolm Tredinnick <[EMAIL PROTECTED]>
wrote:
> On Tue, 2008-02-12 at 18:30 -0800, Julien wrote:
> > Hello,
>
> > The module was not compiled, because it was the __import__ function
> > itself that raised an exception and so didn't have the chance to do
> > the compilation.
>
> > As you've suggested, I tried:
>
> > klass = __import__("myapp", {}, {}, [''])
> > -> Works, returns <module myapp>
>
> > klass = __import__("myapp.forms", {}, {}, [''])
> > -> Works, returns <module myapp.forms>, and compiles "forms.pyc"!!
>
> > klass = __import__("myapp.forms", {}, {}, ['MyModelForm'])
> > -> Works, and returns the same thing as above: <module myapp.forms>
>
> > But, although the module is now compiled, the following still doesn't
> > work:
> > klass = __import__("myapp.forms.MyModelForm", {}, {}, [''])
>
> > For info, MyModelForm is an instance of ModelFormMetaclass. I also
> > tried importing another model, still in vain:
> > klass = __import__("myapp.models.MyOtherModel", {}, {}, [''])
>
> Oh, doh! I'm an idiot. The answer was there all along.
>
> You can't do "import myapp.models.MyOtherModel", because MyOtherModel
> isn't a *module*. It's something inside a module. That's just normal
> Python behaviour.
>
> So you have to do
>
>         module = __import__("myapp.forms", {}, {}, ['MyModelForm'])
>
> (using either 'MyModelForm' or '' in the last component). Then
>
>         klass = module.MyModelForm
>
> Of course, in your case, that means splitting off the last dotted piece
> of the string to work out the form class. This is exactly what we do in
> django.template.loader.find_template_source(), for example, to separate
> the template loader function from the model it's contained in.
>
> I'm so sorry for misleading you for a little while there. Complete brain
> failure on my part. But it all makes perfect sense now.
>
> Regards,
> Malcolm
>
> --
> Depression is merely anger without 
> enthusiasm.http://www.pointy-stick.com/blog/
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to