Alejandro Veintimilla
Alejandro Veintimilla

Reputation: 11543

Django. ImportError. Cannot import Model

This is weird. I can't find the error. I can't run the server (or anything) cause I get an error:

ImportError: cannot import name Libro

So these are the models:

perfiles.models.py-

from django.db import models
from django.contrib.auth.models import User

from libros.models import Libro <- WEIRD ERROR ??¡?

class Perfil(models.Model):
    usuario = models.OneToOneField(User, null=True)
    actualmente_leyendo = models.ForeignKey(Libro, related_name="actualmente_leyendo")
    ...

libros.models.py -

from django.db import models

from perfiles.models import Perfil

    class Libro(models.Model):
        titulo = models.CharField(max_length=255, blank=True)
        autor = models.CharField(max_length=255, blank=True)
        imagen = models.CharField(max_length=255, blank=True)

So, both "libros" and "perfiles" are apps registered on my settings.py and , when I open a ´python manage.py shell´ and run ´from libros.models import Libro´, it works correctly and gives me

(InteractiveConsole)
>>> from libros.models import Libro
>>> Libro
<class 'libros.models.Libro'>

So, where could the error be? and why can the python shell import the model and the other model can't? Any ideas will be helpfull. Thanks.

Upvotes: 1

Views: 2805

Answers (1)

Rod Xavier
Rod Xavier

Reputation: 4043

You are having a circular import error. You are trying to import Libro in perfiles.model and you are trying to import Perfil in libros.model.

You could use django.db.models.loading.get_model to solve this.

You could do something like

from django.db.models.loading import get_model

Libro = get_model('libros', 'Libro')

class Perfil(models.Model):
    usuario = models.OneToOneField(User, null=True)
    actualmente_leyendo = models.ForeignKey(Libro, related_name="actualmente_leyendo")

Or better yet, don't import the model and just pass a string with the format <app>.<model_name> when referencing models from other apps

class Perfil(models.Model):
    usuario = models.OneToOneField(User, null=True)
    actualmente_leyendo = models.ForeignKey('libros.Libro', related_name="actualmente_leyendo")

Upvotes: 4

Related Questions