Home > front end >  ImportError: cannot import name 'views' from 'birds_eye'
ImportError: cannot import name 'views' from 'birds_eye'

Time:10-20

I've recently started to learn how to build django projects with multiple apps. I have learnt that by using from . import views I can import the different views from the current directory that I am in. However, when using this method, the prompt would give me an error saying: ImportError: cannot import name 'views' from 'birds_eye'

The following is my current directory tree of my django project:

birds_eye
|- accounts (app folder)
|- birds_eye (actual project folder)
|- clubs (app folder)
|- events (app folder)
|- posts (app folder)
|- static
|- templates

And this is the actual code of what is happening:

birds_eye
|- birds_eye (actual project folder)
    |- urls.py
from django.contrib import admin
from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.HomePage.as_view(), name="home"),
    path("admin/", admin.site.urls),
    path("test/", views.TestPage.as_view(), name="test"),
    path("thanks", views.ThanksPage.as_view(), name="thanks"),
    path('accounts/', include("accounts.urls", namespace="accounts")),
    path("accounts/", include("django.contrib.auth.urls")),

    # Events --> Calendar, Posts --> Feed | Expected to finish later on. Uncomment when done.
    # path("posts/", include("posts.urls", namespace="posts")),
    # path("events/", include("events.urls", namespace="events")),
    
    path("clubs/", include("clubs.urls", namespace="clubs")),
    path('surveys', include('djf_surveys.urls')),
]

Is there any solution to this?
(I can edit the question in order to provide more resources from my project)

CodePudding user response:

You don't have a views.py file in the same directory as your urls.py file. I assume your views are in your other apps (clubs, posts, etc)?

You would be better to import each view directly from those apps, e.g. in your urls.py

from ..clubs.views import ...

Alternatively, if you do want to carry on down the route you are on. Create a views.py file in your birds_eye folder (same as urls.py) and import all the views into there using the same approach as I put above. You should then be able to import views in your current directory and all the views you need will be in there.

CodePudding user response:

The error indicates that you have missed views.py file inside the folder where you have urls.py. You can create a new one or import the view functions from another app or folder as AshSmith88 explained. You might want to check alternative relative import examples from here

  • Related