Django 1.11: ImportError: cannot import name [view] - django

I'm trying to add ChartsJS as an extra view in my Django App but I keep getting an Import Error. I have no idea why. I don't have any circular dependencies as far as I can find. Similar StackOverflow questions don't seem to match the problem. I'm totally stuck.
The problematic view is Analytics view.
project/app/urls.py:
# -*- coding: utf-8 -*-
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
from django.conf.urls import url
from future import standard_library
from survey.views import ConfirmView, IndexView, SurveyCompleted, SurveyDetail, AnalyticsView
from survey.views.survey_result import serve_result_csv
standard_library.install_aliases()
urlpatterns = [
url(r'^$', IndexView.as_view(), name='survey-list'),
url(r'^(?P<id>\d+)/', SurveyDetail.as_view(), name='survey-detail'),
url(r'^csv/(?P<pk>\d+)/', serve_result_csv, name='survey-result'),
url(r'^(?P<id>\d+)/completed/', SurveyCompleted.as_view(),
name='survey-completed'),
url(r'^(?P<id>\d+)-(?P<step>\d+)/', SurveyDetail.as_view(),
name='survey-detail-step'),
url(r'^confirm/(?P<uuid>\w+)/', ConfirmView.as_view(),
name='survey-confirmation'),
url(r'^analytics/$', AnalyticsView.as_view(),
name='analytics-view'),
]
project/app/views/analytics_view.py:
# -*- coding: utf-8 -*-
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
from builtins import super
from future import standard_library
from django.views.generic.base import TemplateView
from django.contrib.auth.models import User
standard_library.install_aliases()
import arrow
class AnalyticsView(TemplateView):
template_name = "survey/analytics.html"
...
I've read it may be to do with Settings, but I can't see any configuration problems there -
project/settings.py:
ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_URL = '/bootstrap_admin/static/'
STATICFILES_DIRS = [
os.path.normpath(os.path.join(ROOT, '..', "survey", "static")),
]
Traceback:
Unhandled exception in thread started by <function wrapper at 0x05CBB9F0>
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run
self.check(display_num_errors=True)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config
return check_resolver(resolver)
File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver
return check_method()
File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 254, in check
for pattern in self.url_patterns:
File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Users\ronaldg\Documents\csa-survey\urls.py", line 18, in <module>
url(r'^survey/', include('survey.urls')),
File "C:\Python27\lib\site-packages\django\conf\urls\__init__.py", line 50, in include
urlconf_module = import_module(urlconf_module)
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Users\ronaldg\Documents\csa-survey\survey\urls.py", line 9, in <module>
from survey.views import ConfirmView, IndexView, SurveyCompleted, SurveyDetail, AnalyticsView
ImportError: cannot import name AnalyticsView
Any ideas what I'm doing wrong?

The code you posted shows that your AnalyticsView is in its own file; you need to import that file.
from survey.views.analytics_view import AnalyticsView

Related

Django import my app models AppRegistryNotReady

I will import my models in celery.py. But when I import and run the runserver command, I get the following error:
File "/directory/manage.py", line 22, in <module>
main()
File "/directory/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/directory/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
utility.execute()
File "/directory/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 363, in execute
settings.INSTALLED_APPS
File "/directory/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__
self._setup(name)
File "/directory/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup
self._wrapped = Settings(settings_module)
File "/directory/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
......
File "/directory/__init__.py", line 1, in <module>
from .celery import app as celery_app
File "/directory/celery.py", line 9, in <module>
from apps.models import Model1
File "/directory/apps/models.py", line 2, in <module>
from django.contrib.auth.models import User, AbstractUser
File "/directory/venv/lib/python3.9/site-packages/django/contrib/auth/models.py", line 3, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "/directory/venv/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line 48, in <module>
class AbstractBaseUser(models.Model):
File "/directory/venv/lib/python3.9/site-packages/django/db/models/base.py", line 108, in __new__
app_config = apps.get_containing_app_config(module)
File "/directory/venv/lib/python3.9/site-packages/django/apps/registry.py", line 253, in get_containing_app_config
self.check_apps_ready()
File "/directory/venv/lib/python3.9/site-packages/django/apps/registry.py", line 136, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
My import code line in celery.py:
from app.models import model1, model2
You can try adding this line to your settings.py file:
import django
django.setup()
See here for solution.
if it doesn't work, this might be what you need:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project.settings")
and these lines:
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
If the first solution doesn't work here the alternative solution.
Finally, there is such a solution:
import django
# some variable declarations
world_mapping = {
'osm_id': 'osm_id',
}
if __name__ == '__main__':
django.setup()
# import AFTER setup
from app.models import WorldBorder
# from now I can access WorldBorder!!
I solved it by copying all tasks from celery.py to app tasks.py.
It also fixes itself when I delete celery related lines from __init__.py file.

Django 'ImportError: cannot import name url'

Hi could anyone help me fix 'ImportError: cannot import name url' problem?
I have followed tutorial here https://docs.djangoproject.com/en/1.9/intro/tutorial01/
I have tried another tutorial https://docs.djangoproject.com/zh-hans/2.0/ref/urls/#django.urls.include
but neither of them worked
My Django version is 1.11.20
Performing system checks...
Unhandled exception in thread started by Traceback
(most recent call last):
File
"/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py",
line 228, in wrapper fn(*args, **kwargs)
File
"/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py",
line 124, in inner_run self.check(display_num_errors=True)
File
"/usr/local/lib/python2.7/dist-packages/django/core/management/base.py",
line 359, in check
include_deployment_checks=include_deployment_checks,
File
"/usr/local/lib/python2.7/dist-packages/django/core/management/base.py",
line 346, in _run_checks return
checks.run_checks(**kwargs)
File
"/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py",
line 81, in run_checks new_errors =
check(app_configs=app_configs)
File
"/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py",
line 16, in check_url_config return
check_resolver(resolver)
File
"/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py",
line 26, in check_resolver return check_method()
File
"/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py",
line 256, in check for pattern in
self.url_patterns:
File
"/usr/local/lib/python2.7/dist-packages/django/utils/functional.py",
line 35, in get res =
instance.dict[self.name] = self.func(instance)
File
"/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py",
line 407, in url_patterns patterns =
getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File
"/usr/local/lib/python2.7/dist-packages/django/utils/functional.py",
line 35, in get res =
instance.dict[self.name] = self.func(instance)
File
"/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py",
line 400, in urlconf_module return
import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/init.py", line 37, in
import_module
import(name) File "/home/adduser/cantera_correction/mysite/urls.py", line 16, in
from
django.conf.urls import include, path
ImportError: cannot import name path
path was introduced in django since Django 2.0. So, if you are using Django 1.11, then you can't use it. You need to define urls like this:
from django.conf.urls import url, include
urlpatterns = [
# rest of the urls
url(r'^$', HomeView.as_view()),
]
correct your imports to this:
from django.urls import path, include
This code will work for you.
from django.urls import path
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
]

How to fix django app error in edx-platform

I want to add a new app in the https://github.com/edx/edx-platform.
I am following this https://docs.djangoproject.com/en/2.2/intro/tutorial01/ document
/edx/app/edxapp/edx-platform/myapp/url.py
from django.conf.urls import url
from . import views
urlpatterns = [
url('', views.hello, name = 'hello'),
]
/edx/app/edxapp/edx-platform/lms/envs/common.py
INSTALLED_APPS = [
# Standard ones that are always installed...
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.humanize',
'django.contrib.messages',
'django.contrib.redirects',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.staticfiles',
'djcelery',
'myapp',
.............
/edx/app/edxapp/edx-platform/lms/urls.py
urlpatterns = [
url(r'^$', branding_views.index, name='root'), # Main marketing page, or redirect to courseware
url(r'', include('student.urls')),
# TODO: Move lms specific student views out of common code
url(r'^dashboard/?$', student_views.student_dashboard, name='dashboard'),
url(r'^change_enrollment$', student_views.change_enrollment, name='change_enrollment'),
url(r'^myapp/', include('myapp.urls')),
My Error
Traceback (most recent call last):
File "manage.py", line 123, in <module>
execute_from_command_line([sys.argv[0]] + django_args)
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/base.py", line 327, in execute
self.check()
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config
return check_resolver(resolver)
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver
return check_method()
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 256, in check
for pattern in self.url_patterns:
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 407, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 400, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/edx/app/edxapp/edx-platform/lms/urls.py", line 6, in <module>
from django.conf.urls import include, url, path
ImportError: cannot import name path
Where I am going wrong. please let me know.
File "/edx/app/edxapp/edx-platform/lms/urls.py", line 6, in <module>
from django.conf.urls import include, url, path
ImportError: cannot import name path
The above error is saying that you can't import path from django.conf.urls. It seems you are using older version of django. so, try the following command to install old version.
$ pip install Django==1.11
and go to file /edx/app/edxapp/edx-platform/lms/urls.py and remove path from import. Then it looks like below.
from django.conf.urls import include, url

Django AppRegistryNotReady when defining a model

I wanted to add the first model to an already working app, and now I can't start it because it always gives AppRegistryNotReady. This does only happen, if my model MailLog is child of models.Model.
from __future__ import unicode_literals
from django.db import models
#class MailLog(models.Model): # like this, it crashes
class MailLog(): # like this, it works
# Field definitions
recipient = models.EmailField()
created = models.DateTimeField(auto_now_add=True)
template = models.CharField(max_length=500)
error = models.TextField(null=True)
def __str__(self):
return self.recipient+" "+self.template+"("+str(self.created)+")"
The error occurs no matter what's inside the class, even if there is only a pass. However, I can import my models in the admin.py, and it crashes when I import from a file I called core.py. That file looks like this:
import boto3
from botocore.exceptions import ClientError
from django.template import loader
from django.conf import settings
from .templates import *
from .models import MailLog
The traceback looks like this
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/core/management/__init__.py", line 316, in execute
settings.INSTALLED_APPS
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup
self._wrapped = Settings(settings_module)
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/conf/__init__.py", line 97, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/home/niels/anaconda3/envs/app/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/niels/Dokumente/jobapp/deploy/backend/settings.py", line 255, in <module>
django.setup()
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/apps/config.py", line 90, in create
module = import_module(entry)
File "/home/niels/anaconda3/envs/app/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/niels/Dokumente/jobapp/deploy/ses_mail/__init__.py", line 1, in <module>
from .core import send
File "/home/niels/Dokumente/jobapp/deploy/ses_mail/core.py", line 7, in <module>
from .admin import MailLog
File "/home/niels/Dokumente/jobapp/deploy/ses_mail/admin.py", line 2, in <module>
from .models import *
File "/home/niels/Dokumente/jobapp/deploy/ses_mail/models.py", line 6, in <module>
class MailLog(models.Model):
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/db/models/base.py", line 105, in __new__
app_config = apps.get_containing_app_config(module)
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/apps/registry.py", line 237, in get_containing_app_config
self.check_apps_ready()
File "/home/niels/anaconda3/envs/app/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
You should not be importing Django models in your app's __init__ (or causing them to be imported by importing from core. If you use an empty __init__.py it should stop the error.

cannot import LoginView?

i'm learning some things about Django 1.9 and i want to make a login form but with class-based views.
This is mi view code:
from django.shortcuts import render
from django.contrib.auth.views import LoginView
class AlumnoLoginView(LoginView):
template_name = "alumno/login.html"
redirect_authenticated_user = True
And this is my urls code:
from django.conf.urls import url, include
from .views import AlumnoLoginView
app_name = 'alumno'
urlpatterns = [
url(r'^login/$', AlumnoLoginView.as_view(), name="login"),
]
This make an error:
ImportError: cannot import name LoginView
But if I delete the code inside urls nothing happens.
This is the full error trace (with François change):
Unhandled exception in thread started by <function wrapper at 0x7f044ad8ac08>
Traceback (most recent call last):
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run
self.check(display_num_errors=True)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check
include_deployment_checks=include_deployment_checks,
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver
for pattern in resolver.url_patterns:
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/plafhz/Envs/StudentAdmin/studentadmin/studentadmin/urls.py", line 21, in <module>
url(r'^alumno/', include('alumno.urls')),
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 52, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/plafhz/Envs/StudentAdmin/studentadmin/alumno/urls.py", line 3, in <module>
from alumno.views import AlumnoLoginView
File "/home/plafhz/Envs/StudentAdmin/studentadmin/alumno/views.py", line 3, in <module>
from django.contrib.auth.views import LoginView as BaseLoginView
ImportError: cannot import name LoginView
What is wrong?
How I fix it?
Thank :)
Class-based views LoginView and LogoutView are introduced on Django 1.11 and function-based views 'login' and 'logout' are deprecated since then.
You can use class-based views LoginView and LogoutView like this:
from django.contrib.auth.views import LoginView, LogoutView
urlpatterns = [
url(r'^login/$', LoginView.as_view(template_name='...'), name="login"),
]
There's no view called LoginView in django.contrib.auth.views
I think you need.
from django.contrib.auth.views import login
LoginView only available from Django 1.11
cannot import LoginView?
You must be using lower version of django ..Login view supported only in 1.11 or higher version..
You need to install 1.11 or higher version
pip install django==1.11