I am trying to register my model into the admin view using the code:
from django.contrib import admin
from mysite.polls.models import Choice, Question
# Register your models here.
admin.site.register(Question)
admin.site.register(Choice)
But i am getting the error: (mysite is the project name and polls is the app name)
from mysite.polls.models import Choice, Question
ModuleNotFoundError: No module named 'mysite.polls'
I am following the 3.1 documentation which tells us to use:
from django.contrib import admin
from myproject.myapp.models import Author
admin.site.register(Author)
While registering your model in admin.py
Is your polls
directory in a directory named mysite
?
Is polls
listed in your INSTALLED_APPS setting?
Do you have an apps.py
file in the mysite.polls
directory?
Do you have an empty __init__.py
file in mysite.polls
?
What version of Python are you using? What version of Django?
-
Yes polls
is a directory in a directory named mysite
-
Yes polls
is listed in my INSTALLED_APPS
setting as:
# Application definition
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
- Yes i have an
apps.py
file in polls
directory.
- Yes there is an empty
__init__.py
file in polls
directory
Python version = 3.8.5 and Django version = 3.1.4
First i have used the command django-admin startproject mysite
Then, i created a app named polls using the command python manage.py startapp polls
Now i have 2 models named Question
and Choice
in my polls
app and in order to register them i have followed the step given in the documentation
Link: The Django admin site | Django documentation | Django
Just have replaced myproject
with mysite
as it is the name of my project and myapp
with polls
as that is the name of my app.
The “project-level” mysite
is your base directory - polls
is not within the “app” mysite
, it’s within the “project” mysite
. Your reference to your models is then polls.models
, not mysite.polls.models
. (Notice that you reference it in your INSTALLED_APPS as polls.apps
, not mysite.polls.apps
.)
I think we are not supposed to keep an app within app anyways, then why is that (myproject.myapp.models
)given in the documentation? Isn’t it giving unnecessary confusion to someone following the documentation:
from django.contrib import admin
from myproject.myapp.models import Author
admin.site.register(Author)
I agree, I have filed a documentation ticket for this. (There’s another situation where this would be valid, and that’s when you have your manage.py outside your project. That’s how it used to be done long ago.)
You can try to import it like this:
from django.contrib import admin
from .models import Choice, Question
admin.site.register(Question)
admin.site.register(Choice)
Because models.py
and admin.py
in the same directory and you can access any file in the same directory with a dot.