2

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.

SverkerSbrg
  • 503
  • 1
  • 9
  • 23
  • 1
    Why do you need to import forms within models? There's not usually any need for that. – Daniel Roseman Aug 15 '14 at 06:57
  • Usually not, working with a generic relationship and need to be able to access the correct from from the model class – SverkerSbrg Aug 15 '14 at 06:58
  • 1
    Most likely you are doing something wrong, namely models should not be concerned about forms at all. If you are absolutely sure you want to follow this path, try moving `from .forms import foo` into the method that use `foo`. It should break cyclic import, but will import `forms` each time the method is invoked – J0HN Aug 15 '14 at 07:02
  • How would you handle form input of an object with a generic relationship to a model of a specific type (inheriting from an abstract model)? I want to create both objects at the sametime within the same view. – SverkerSbrg Aug 15 '14 at 07:12
  • 1
    You're really going to need to show that code then. The very fact that you mentioned the view is a hint that things are far too coupled: maybe the logic belongs in the view itself? – Daniel Roseman Aug 15 '14 at 07:30

1 Answers1

1

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.

Stuart Leigh
  • 826
  • 4
  • 6