ModuleNotFoundError: No module named 'src'

Question:

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

- 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’

Asked By: MHB

||

Answers:

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.

Answered By: ms-

I got the same problem, IDE may use red underline but this code is still correct:

from pages.views
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.