Sphinx: runtime error django 1.9 - django

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()

Related

"Model class myproject.models.MyModel doesn't declare an explicit app_label during" During Django test

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',
]

Django-Sphinx RuntimeError: Model class models.Project doesn't declare

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

The Wonderful Apps aren't loaded yet Error

I've searched SO and Google and can't find an answer to my problem.
I've launched my virtualenv and ran this command in the terminal:
python bin/process_messages.py
and this error occurs:
Stacktrace:
Traceback (most recent call last):
File "bin/process_messages.py", line 6, in <module>
from xyz.models import get_sku
File "/Users/myname/.environments/xyz_env/lib/python3.6/site-packages/xyz/models.py", line 19, in <module>
class Suppliers(models.Model):
File "/Users/myname/.environments/xyz_env/lib/python3.6/site-packages/django/db/models/base.py", line 110, in __new__
app_config = apps.get_containing_app_config(module)
File "/Users/myname/.environments/xyz_env/lib/python3.6/site-packages/django/apps/registry.py", line 247, in get_containing_app_config
self.check_apps_ready()
File "/Users/myname/.environments/xyz_env/lib/python3.6/site-packages/django/apps/registry.py", line 125, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
I thought it wasn't running django.setup so I added that to the script. Here is my code:
#!/usr/bin/env python
import os
import django
import boto3
from xyz.settings import SQS_QUEUE_NAME
from xyz.models import get_sku
__author__ = 'me'
def check_django_environment(default_settings):
# Environment setup for Django project files:
os.sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if not os.environ.get('DJANGO_SETTINGS_MODULE'):
# Don't override settings if it is specified.
os.environ['DJANGO_SETTINGS_MODULE'] = default_settings
from django.conf import settings
return getattr(settings, 'DEBUG', None)
check_django_environment('xyz.settings')
django.setup()
# Get the service resource
sqs = boto3.resource('sqs')
# Get the queue
queue = sqs.get_queue_by_name(QueueName=SQS_QUEUE_NAME)
for message in queue.receive_messages():
print(message)
if message.message_attributes is not None:
print(message.message_attributes)
#sku = message.message_attributes
db_sku = get_sku(sku)
print(db_sku)
break
My Installed apps:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'xyz',
]
By importing get_sku, you are importing your models before django.setup() has run. You need to move this import down so it happens after django.setup().
In a stand-alone script that uses Django, I generally have two groups of imports. The first contains the bare minimum to get Django setup, the second contains all the other imports, including models etc.:
#!/usr/bin/env python
import os
import django
__author__ = 'me'
def check_django_environment(default_settings):
# Environment setup for Django project files:
os.sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if not os.environ.get('DJANGO_SETTINGS_MODULE'):
# Don't override settings if it is specified.
os.environ['DJANGO_SETTINGS_MODULE'] = default_settings
from django.conf import settings
return getattr(settings, 'DEBUG', None)
check_django_environment('xyz.settings')
django.setup()
import boto3
from xyz.settings import SQS_QUEUE_NAME
from xyz.models import get_sku
In addition to knbk's answer, you can also just use manage.py.
Here's an example script, let's say script.py:
from xyz.models import get_sku
if __name__ == '__main__':
print(get_sku)
And you run it like:
./manage.py shell < script.py
Maybe not what you're looking for, but worth knowing, nonetheless.

Django1.7 'RemovedInDjango19Warning' when using apache with mod_wsgi

i am using Django version 1.7 for an application,
everything was running good in my developpement PC (i was runnin it using manage.py runserver command.
now i am trying to move it to a production server.
in the production server, everything is still good when running the server using the manage.pycommand.
but accessing the application remotely (via apache2 & mod_wsgi), i get an RemovedInDjango19Warning Exception.
after looking for a solution all i could find is how to ignore theses warnings for manage.py which don't work for me and i don't know how to disable this warnings from wsgi ?
Traceback:
Environment:
Request Method: GET
Request URL: http://192.168.0.17/
Django Version: 1.7.1
Python Version: 3.4.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'rest_framework',
'rest_framework_nested',
'django_gravatar',
'authentication',
'djcelery',
'job',
'seed',
'proxies',
'emails')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in get_response
98. resolver_match = resolver.resolve(request.path_info)
File "/usr/local/lib/python3.4/dist-packages/django/core/urlresolvers.py" in resolve
343. for pattern in self.url_patterns:
File "/usr/local/lib/python3.4/dist-packages/django/core/urlresolvers.py" in url_patterns
372. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python3.4/dist-packages/django/core/urlresolvers.py" in urlconf_module
366. self._urlconf_module = import_module(self.urlconf_name)
File "/usr/lib/python3.4/importlib/__init__.py" in import_module
109. return _bootstrap._gcd_import(name[level:], package, level)
File "/var/www/cvc.ma/CapValue/urls.py" in <module>
6. url(r'^api/v1/auth/', include('authentication.urls')),
File "/usr/local/lib/python3.4/dist-packages/django/conf/urls/__init__.py" in include
28. urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.4/importlib/__init__.py" in import_module
109. return _bootstrap._gcd_import(name[level:], package, level)
File "/var/www/cvc.ma/authentication/urls.py" in <module>
2. from authentication.views import LoginView, LogoutView
File "/var/www/cvc.ma/authentication/views.py" in <module>
4. from rest_framework import permissions, viewsets, status, views
File "/usr/local/lib/python3.4/dist-packages/rest_framework/viewsets.py" in <module>
24. from rest_framework import views, generics, mixins
File "/usr/local/lib/python3.4/dist-packages/rest_framework/views.py" in <module>
11. from rest_framework.request import Request
File "/usr/local/lib/python3.4/dist-packages/rest_framework/request.py" in <module>
20. from rest_framework.settings import api_settings
File "/usr/local/lib/python3.4/dist-packages/rest_framework/settings.py" in <module>
22. from django.utils import importlib, six
File "/usr/local/lib/python3.4/dist-packages/django/utils/importlib.py" in <module>
10. RemovedInDjango19Warning, stacklevel=2)
Exception Type: RemovedInDjango19Warning at /
Exception Value: django.utils.importlib will be removed in Django 1.9.
It's happening because the django.utils.importlib module is removed in Django 1.9, in favor of the importlib in the standard library. Django Rest Framework still uses it.
You can disable the warning by following the instructions on the accepted answer of this question -- How to suppress the deprecation warnings in Django?
Finally, i ended up upgrading to Django1.9 and fixed the migration bugs.
If you just want to silence the warning in mod_wsgi, you may add a configuration directive such as:
WSGIPythonWarnings ignore::DeprecationWarning::
See this blog entry, the release notes (point 15) and the original issue.
In essence, mod_wsgi had no equivalent to the -W control option, so a directive was added. The default must have been kept at "log everything" to be consistent across different wsgi apps.

Django ImportError: cannot import name get_permission_codename

I am doing the tango with django tutorial. I am up to chapter 5 on working with models and I am setting up the admin website. I get this strange error:
ImportError: cannot import name get_permission_codename
This seems to go away when I remove the
admin.autodiscover()
from my project/urls.py. But I am concerned that I will need this down the road.
Here is the Traceback I get when I run the development server:
Environment:
Request Method: GET Request URL: http://127.0.0.1:8000/admin/
Django Version: 1.5.4 Python Version: 2.7.3 Installed Applications:
('django.contrib.auth', 'django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.sites',
'django.contrib.messages', 'django.contrib.staticfiles',
'django.contrib.admin', 'rango') 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
"/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py"
in get_response
103. resolver_match = resolver.resolve(request.path_info) File
"/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py"
in resolve
319. for pattern in self.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py"
in url_patterns
347. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File
"/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py"
in urlconf_module
342. self._urlconf_module = import_module(self.urlconf_name) File
"/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py" in
import_module
35. import(name) File "/home/gpanterov/MyProjects/django/tango_with_django_project/tango_with_django_project/urls.py"
in
6. admin.autodiscover() File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/init.py"
in autodiscover
29. import_module('%s.admin' % app) File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py" in
import_module
35. import(name) File "/usr/local/lib/python2.7/dist-packages/django/contrib/contenttypes/admin.py"
in
5. from django.contrib.admin.checks import InlineModelAdminChecks File
"/usr/local/lib/python2.7/dist-packages/django/contrib/admin/checks.py"
in
6. from django.contrib.admin.utils import get_fields_from_path, NotRelationField, flatten File
"/usr/local/lib/python2.7/dist-packages/django/contrib/admin/utils.py"
in
6. from django.contrib.auth import get_permission_codename
Exception Type: ImportError at /admin/ Exception Value: cannot import
name get_permission_codename
When I remove the admin.autodiscover() line, the development server runs and I am able to get to the admin panel, but when I log in with the superuser password I created earlier, I get the message "You don't have permission to edit anything." and I don't see any of the categories I created.
I got this error when downgrading django from latest version (1.8) to an old version (1.4) for testing.
The problem here is that git doesn't delete .pyc files when switching branches (because they are .gitignore'ed) and python only regenerates them when the corresponding .py file is newer than the .pyc file (see this question for details).
The solution is to delete all *.pyc files in django/contrib/admin and django/contrib/contenttypes directories.
cannot import name get_permission_codename
Make sure u have not install all the version of django in your system.
if there then remove all and install fresh django