简体   繁体   中英

ModuleNotFoundError: No module named 'src'

I'm changing view of homepage with app names pages. I've added pages to settings. this is how directory look like:

  1. trydjango
    • src
      • pages
        • init
        • views
      • products
      • trydjango
        • init
        • settings
        • urls
      • manage

views' code:

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.

def home_view(*args, **kwargs):
    return HttpResponse("<h1>Hello Again</h1>")

urls' code

from django.contrib import admin
from django.urls import path
from src.pages.views import home_view


urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home_view, name='home'),
]

and I see this error when I run server

ModuleNotFoundError: No module named 'src'

First you need to understand what an app in Django is compared to a project. When you register an app django will look in the project root folder when you try to import it.
Your project root is where your manage.py file is. In your case the src folder.
So when you want to import your views module you need to state

    from pages.views 

rather than

    from src.pages.views

I suggest that you read through and follow (by coding it yourself) the Django tutorial to learn more about project structure and creating your own apps with models, urls etc.

我遇到了同样的问题,IDE可能使用红色下划线,但是此代码仍然正确:

from pages.views

我发现如果你按照上面的人所说的将你的 src 文件夹标记为源根目录,红色下划线就会消失!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM