I am attempting to generate a html documentation with Sphinx of a django project. I am getting the following error when executing make html on windows cmd.
My settings.py contains an entry for the application I built, where the
models.py file belongs to. For confidentially reasons, I call it here project_name.
INSTALLED_APPS = [
'project_name.apps.project_nameAppConfig',
'django.contrib.admin',
'django.contrib.sites',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'import_export',
'nested_admin',
'report_builder',
'rest_framework',
'ajax_select',
]
Error Trace:
> C:\django_project\docs\source\models.rst:4: WARNING: autodoc: failed to
> import module 'models'; the following exception was raised: Traceback
> (most recent call last): File
> "C:\Users\...\AppData\Local\Continuum\Anaconda3\lib\site-packages\sphinx\ext\autodoc.py",
> line 658, in import_object
> __import__(self.modname) File "C:\django_project\project_name\models.py", line 8, in <module>
> class Project(models.Model): File "C:\Users\...\AppData\Local\Continuum\Anaconda3\lib\site-packages\django\db\models\base.py",
> line 118, in __new__
> "INSTALLED_APPS." % (module, name) RuntimeError: Model class models.Project doesn't declare an explicit app_label and isn't in an
> application in INSTALLED_APPS.
Thanks for your help!
What solved the issue for me is creating an abstract class and inheriting the other model classes from there instead of directly from the django.db models class. In code something along this lines:
from django.db import models
class BaseModel(models.Model):
class Meta:
abstract = True # specify this model as an Abstract Model
app_label = 'your_project_name'
class Project(BaseModel):
name = models.CharField(max_length=200, unique=True)
description = models.TextField
client = models.CharField(max_length=200)
def __str__(self):
return self.name
...
Got the idea from here: Model class doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
Related
With Django 2.2.9 I'm getting the following error when I try to run ./manage test
File "/home/simernes/workspace/myproject/myapp/test/test_functions.py", line 3, in <module>
from ..functions import make_response
File "/home/simernes/workspace/myproject/myapp/functions.py", line 2, in <module>
from .serializers import MyModelSerializer, \
File "/home/simernes/workspace/myproject/myapp/serializers.py", line 2, in <module>
from .models import MyModel, \
File "/home/simernes/workspace/myproject/myapp/models.py", line 7, in <module>
class MyModel(models.Model):
File "/home/simernes/workspace/myproject/env/lib/python3.7/site-packages/django/db/models/base.py", line 111, in __new__
"INSTALLED_APPS." % (module, name)
RuntimeError: Model class myproject.myapp.models.MyModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
in functions I'm importing the model as follows:
functions.py:
from .models import MyModel
def make_response():
print("lorem ipsum")
It appears that simply by importing something from the file containing a class extending Model this error occurs, because it happens with the following test definition:
from django.test import TestCase
from ..functions import make_response
class MyTestCase(TestCase):
def setUp(self):
pass
def test_make_response(self):
self.assertTrue(True)
Is there any way to solve this?
Installed apps:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'django_filters',
'corsheaders',
'myapp',
]
I have some models including custom user like that:
class User(AbstractUser):
image = models.ImageField(upload_to=get_image_path, blank=True, null=True)
objects = NewUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
def __str__(self):
return self.email
class Meta(AbstractUser.Meta):
swappable = 'stack.User'
That worked just fine with the other models I already have until i'm trying to add just one more class:
class Vote(models.Model):
rate_type = models.BooleanField()
question = models.ForeignKey("Question", related_name='question_rate', on_delete=models.PROTECT)
answer = models.ForeignKey("Answer", related_name='answer_rate', on_delete=models.PROTECT)
user = models.ForeignKey(get_user_model(), on_delete=models.PROTECT)
class Meta:
unique_together = [('question', 'user'), ('answer', 'user'), ]
Unfortunately i get en error trying to migrate:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/artem/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/artem/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/artem/.local/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/artem/.local/lib/python3.5/site-packages/django/core/management/base.py", line 335, in execute
output = self.handle(*args, **options)
File "/home/artem/.local/lib/python3.5/site-packages/django/core/management/commands/makemigrations.py", line 159, in handle
migration_name=self.migration_name,
File "/home/artem/.local/lib/python3.5/site-packages/django/db/migrations/autodetector.py", line 44, in changes
changes = self._detect_changes(convert_apps, graph)
File "/home/artem/.local/lib/python3.5/site-packages/django/db/migrations/autodetector.py", line 192, in _detect_changes
self._build_migration_list(graph)
File "/home/artem/.local/lib/python3.5/site-packages/django/db/migrations/autodetector.py", line 270, in _build_migration_list
resolved_app_label, resolved_object_name = getattr(settings, dep[1]).split('.')
File "/home/artem/.local/lib/python3.5/site-packages/django/conf/__init__.py", line 57, in __getattr__
val = getattr(self._wrapped, name)
AttributeError: 'Settings' object has no attribute 'stack.User'
I am puzzled of this because i didn't change neither settings.py nor anything else. I can just remove reference to user in "Vote" class and it becomes ok again but unfortunately i need to keep it here. Most of the other models in the same file do have same reference to user class via ForeignKey and "get_user_model()" function (perhaps i tried to switch it with user class itself - same result)- and it works with only difference i added them few migrations ago.
django version 2.0.2
from settings.py:
# Application definition
INSTALLED_APPS = [
'stack.apps.StackConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
AUTH_USER_MODEL = 'stack.User'
wsgi.py:
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "StackOverflow.settings")
application = get_wsgi_application()
apps.py:
class StackConfig(AppConfig):
name = 'stack'
Maybe anybody faced it ever or just knows the solution of how to get rid of this error?
stack app should be added to your INSTALLED_APPS setting:
INSTALLED_APPS = [
'stack.apps.StackConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'stack',
]
AUTH_USER_MODEL = 'stack.User'
Also to specify model in ForeignKey, you can use settings.AUTH_USER_MODEL:
from django.conf import settings
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
The actual reason was:
class Meta(AbstractUser.Meta):
swappable = 'stack.User'
Proper using of this is placed here https://code.djangoproject.com/wiki/ContribAuthImprovements#Solution%202c:%20Generic%20swappable%20models
and my variant is not correct at all as it showed in the docs.But more important that i even don't need these lines at all. I couldn't even pay attention on this initially because this code already was for pretty long time and somehow it worked because insertion of Meta class doesn't require changing of database per se. So 'makemigrations' cmds just considered that nothing was changed unless actual addition was done
Another possible solution
In my case migrations/__init__.py was missing from my app (in OPs case stack) folder.
So as a solution, I followed the steps bellow:
Create migrations/__init__.py in any app/folder missing it (e.g. stack).
Clear migrations and pycache files: find . -path "*/migrations/*.py" -not -name "__init__.py" -delete && find . -path "*/migrations/*.pyc" -delete
Makemigrations: python manage.py makemigrations
Migrate: python manage.py migrate
Those steps were sufficient in my case.
Currently I'm using Django 1.9 and Django Rest Framework. I'm attempting to use Sphinx and it's autodoc functions, but I'm hitting an error on make html. The models.py does not import.
myapp/
manage.py
index.rst
myapp/
__init__.py
settings.py
users/
models.py
source/
modules.rst
users.rst
settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'myapp',
'users',
)
and the error I get is:
WARNING: /home/sestrella/Devel/leroi-angular/source/customers.rst:10: (WARNING/2) autodoc: failed to import module u'users.models'; the following exception was raised:
Traceback (most recent call last):
File "/home/me/.virtualenvs/myapp/local/lib/python2.7/site-packages/sphinx/ext/autodoc.py", line 657, in import_object
__import__(self.modname)
File "/home/me/Devel/myapp/users/models.py", line 3, in <module>
from django.contrib.auth.models import User, Group
File "/home/me/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/contrib/auth/models.py", line 6, in <module>
from django.contrib.contenttypes.models import ContentType
File "/home/me/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/contrib/contenttypes/models.py", line 161, in <module>
class ContentType(models.Model):
File "/home/me/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/db/models/base.py", line 112, in __new__
"INSTALLED_APPS." % (module, name)
RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
/home/me/Devel/myapp/source/modules.rst:4: WARNING: toctree contains reference to nonexisting document u'source/ users'
modules.rst
myapp
=============
.. toctree::
:maxdepth: 4
users
and users.rst
users
================
Modules
----------
users.models
----------------------
.. automodule:: users.models
:members:
:undoc-members:
:show-inheritance:
Why does the users.models fail to import? I do use the ContentType model in my users.models as a generic relation.
I don't know if this is an error fix, or a workaround:
in conf.py, add:
import django
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
django.setup()
I keep receiving the error Could not import movies.views. Error was: No module named models
Here is my traceback:
Environment:
Request Method: GET
Request URL: http://localhost:8000/movies/awesome-movie/
Django Version: 1.3.1
Python Version: 2.7.3
Installed Applications:
['django.contrib.auth',
'username_patch',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.flatpages',
'south',
'tagging',
'tagging_autocomplete',
'accounts',
'movies',
'tracking',
'djcelery',
'pagination']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'pagination.middleware.PaginationMiddleware')
Traceback:
File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
101. request.path_info)
File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
252. sub_match = pattern.resolve(new_path)
File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
252. sub_match = pattern.resolve(new_path)
File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
158. return ResolverMatch(self.callback, args, kwargs, self.name)
File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in _get_callback
167. raise ViewDoesNotExist("Could not import %s. Error was: %s" % (mod_name, str(e)))
Exception Type: ViewDoesNotExist at /movies/awesome-movie/
Exception Value: Could not import movies.views. Error was: No module named models
I am not sure why I have this error. My code is as follows...
I have an django app called tracking and another called movies. I have a python file called tracking.py in the tracking app it consists of the following code:
filmlibrary/tracking/tracking.py
from movies.models import Movie
from tracking.models import MovieView
import os
import base64
def tracking_id(request):
try:
return request.session['tracking_id']
except KeyError:
request.session['tracking_id'] = base64.b64encode(os.urandom(36))
return request.session['tracking_id']
def log_movie_view(request, movie):
t_id = tracking_id(request)
try:
v = MovieView.objects.get(tracking_id=t_id, movie=movie)
v.save()
except MovieView.DoesNotExist:
v = MovieView()
v.movie = movie
v.ip_address = request.META.get('REMOTE_ADDR')
v.tracking_id = t_id
v.user = None
if request.user.is_authenticated():
v.user = request.user
v.save()
The above is pretty basic stuff. My views.py in my movies app uses the tracking.py file here:
filmlibrary/movies/views.py
#login_required
def movie_details(request, slug, template_name="movies/movie_detail.html"):
movie = get_object_or_404(Movie, slug=slug)
movie.tracking_id = tracking.tracking_id(request)
movie.save()
tracking.log_movie_view(request, movie)
context = RequestContext(request, {'movie': movie })
if movie:
try:
screener = movie.moviemedia_set.get(movie_type='screener')
.... continued
UPDATE:
Here are the contents of filmlibrary/tracking/models.py
from django.db import models
from django.contrib.auth.models import User
from movies.models import Movie
class PageView(models.Model):
class Meta:
abstract = True
date = models.DateTimeField(auto_now=True)
ip_address = models.IPAddressField()
user = models.ForeignKey(User, null=True)
tracking_id = models.CharField(max_length=50, default='')
class MovieView(PageView):
movie = models.ForeignKey(Movie)
The error appears to come from the import line from tracking.models import MovieView in the tracking.py file and I am not sure why. As soon as I comment out that line the error goes away but then of course I'll have new errors about MovieView not existing as expected. I don't see anything wrong with that import line in tracking.py.
Does anyone have any suggestions as to why I receive that error and how I can resolve this?
Can you try
from models import MovieView
instead of
from tracking.models import MovieView
The reason being both models.py and tracking.py are in the same app folder "tracking", you don't need to write tracking.models, this will make Django think that you have a folder named models inside the tracking directory.
Though this is a good solution in some cases, this error can also be caused by app name conflicts with built in apps.
I know that our team has encountered this error and it was because of the actual app name. This is also important to note, because you won't be able to pull in models to other apps if that is the case.
#You cannot use this format out of scope
from models import Test
#You can use this both in and out of scope in Django
from myapp.models import Test
If the second example isn't working in your Django project you may be using a conflicting app name. Good examples of unusable built in apps include (but are not limited to) "tests", and "admin".
I would caution against a bandaid fix and investigate your app name closely.
I was trying to implement a rating system that receives the information that a user submits.
But I was just wondering if it's possible to have two classes in one models file and get Could not import myapp.comments.views.stars. View does not exist in module myapp.comments.views.
In my models file, I have
class CommentWithRating(Comment):
rating = models.IntegerField()
def save(self, *args, **kwargs):
self.content_object.rating.add(score=self.rating, user=self.user, ip_address=self.ip_address)
super(CommentWithRating, self).save(*args, **kwargs)
class Rating(models.Model):
first_name = models.charField(maxlength=30)
last_name = models.charField(maxlength=30)
department = models.charField(maxlength=30)
comment = models.charField(maxlength=10000)
communi_rating = models.IntegerField()
prepar_rating = models.IntegerField()
interact_rating = models.IntegerField()
help_rating = models.IntegerField()
By the way, stars is a html file. Any ideas?
This is my views,
from django.shortcuts import render_to_response, render
from django.http import HttpResponse
from models import CommentWithRating
def stars(request):
return render(request, 'star.html', {'score': ''})
My error message is simply,
Could not import myapp.comments.views.stars. View does not exist in module
myapp.comments.views.
My traceback is,
Environment:
Request Method: GET
Django Version: 1.4
Python Version: 2.7.2
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'registration',
'django.contrib.admin',
'djangoratings')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
101. request.path_info)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
300. sub_match = pattern.resolve(new_path)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
209. return ResolverMatch(self.callback, args, kwargs, self.name)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py" in callback
216. self._callback = get_callable(self._callback_str)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/functional.py" in wrapper
27. result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py" in get_callable
101. (lookup_view, mod_name))
Exception Type: ViewDoesNotExist at /rating/
Exception Value: Could not import myapp.comments.views.stars. View does not exist in module >myapp.comments.views.`
Yeah, that's definitely possible.
Try doing a
python ./manage.py shell
and then importing the model or view that is giving you the problem. That might end up giving you more useful debugging information.
(from Django views does not exist or could not import)