I am trying to import views.py to urls.py using from . import views but I keep getting an import error

Question:

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path("", views.home),
    path("predict/", views.predict),
    path("predict/result", views.result)

the traceback is

File "C:UsersuserPycharmProjectsDiabetes PredictionDiabetes_PredictionDiabetes_Predictionurls.py", line 19, in
from . import views
ImportError: attempted relative import with no known parent package

Asked By: Maxwell Oduor

||

Answers:

You are mixing up your project level urls.py with your app urls.py. Your project urls.py is found in the directory containing your settings.py. It should look like this:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]

Your app urls.py should be created in your app directory i.e. where you have your views and models. Create a file named urls.py in that directory. It should look like this:

from django.urls import path

from . import views

app_name = 'myapp'
urlpatterns = [
    path(" ", views.home),
    path("predict/", views.predict),
    path("predict/result", views.result)

OP did not write app name in settings.py. Include your app name in settings.py as shown below:

INSTALLED_APPS = [
    # Default apps
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # My apps
    'myapp',     
]

Please read as you seem to be mixing up a lot of things. Also read the docs I included A typical Django project is made up of one or more apps. You create your project using the command django-admin startproject your_project_name . and you create your app using the following command python manage.py startapp your_app_name. Please make sure you’re not mixing up both. Also make sure you included your appname in INSTALLED_APPS list in your settings.py See docs for more.

Answered By: journpy

Replace the code :

from django.contrib import admin
from django.urls import path
from your_appname import views # change here. 

urlpatterns = [
    path('admin/', admin.site.urls),
    path("", views.home),
    path("predict/", views.predict),
    path("predict/result", views.result)

make sure in your settings.py :

INSTALLED_APPS = [
    
    #others

    # internal app
    'your_appname',     
]
Answered By: Fazle Rabbi