Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Build a Social Network with Flask Broadcasting Stream Templates

Getting ImportError: cannot import name when trying to separate models to different files. Help!

I tried to separate the contents of the models.py to separate files.

Originally we had models.py(database, User and Post). Now, I have the following:

.
+-- app.py
+-- forms.py
+-- templates
+-- static
+-- models
|   +-- user.py
|   +-- post.py
+-- common
|   +-- database.py

As a result of the separation, the two classes User which are in models.user.py and Post in models.post.py are now importing each other. (sort of cyclic dependency)

Moreover, I could not make the app work anymore now that the "stream" feature is now implemented. Traceback (most recent call last):

  File "app.py", line 5, in <module>
    import forms
  File "C:\social_network_app\forms.py", line 6, in <module>
    from models.user import User
  File "C:\social_network_app\models\user.py", line 8, in <module>
    from models.post import Post
  File "C:\social_network_app\models\post.py", line 4, in <module>
    from models.user import User
ImportError: cannot import name 'User'

How to resolve this?

Thanks in advance.

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

Do you have an __init__.py file in both the common and models directories? The file can be empty.

1 Answer

Patriot Rika
Patriot Rika
3,739 Points

I have the same problem, this is how my files are . app.py forms.py templates static models database.py init.py (empty) sc (the venv)

This is what i get

Traceback (most recent call last): File "C:\Users\Admin\Py_Projects\Social_Network_Python\app.py", line 7, in <module> import forms File "C:\Users\Admin\Py_Projects\Social_Network_Python\forms.py", line 6, in <module> from models import User File "C:\Users\Admin\Py_Projects\Social_Network_Python\models.py", line 62, in <module> class Post(Model): File "C:\Users\Admin\Py_Projects\Social_Network_Python\models.py", line 66, in Post related_name='posts' TypeError: init() missing 1 required positional argument: 'model'

Thank you in advance for your help