Search code examples
pythondjangocyclic-reference

Cyclic imports within django subapps


I'm working on a django project where i have the following setup

project
    /products
        /product1
            /models.py
            /forms.py
        /productN
    /otherapps

#models.py
from .forms import foo
...

#forms.py
from .models import bar

You see the cyclic imports. I've tried a number of combinations but i cant seem to get it right. I'd rather not move the code in forms.py to models.py

I've tried:

from products import *
from products.product1 import *
from products.product1.form import *

import products
import products.product1
import products.product1.form

Some help would be much appreciated.


Solution

  • In models.py move your

    from .forms import foo
    

    to inside the method that actually needs to use foo. This will stop it from importing until that method is called rather than as soon as models.py is imported. This isn't best practise and if you use foo in lots of places then it will be a pain to maintain but it should fix the circular import.