I have a coding interview tomorrow (my first ever! Super excited/nervous) and am working to bring an old project of mine back to life and updated: a producthunt clone built in Django/Python.
Everything used to run fine with it and now, after git cloning it into a ubuntu virtualbox and bringing things up to date in its virtualenv, I'm stuck with the following error and have come up empty handed after hours of troubleshooting and researching similar issues on stackoverflow. Any help is appreciated.
The error: 'AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF''
Settings and output:
settings.py
"""
Django settings for producthunt project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#(b=ndac#9k%w#y7(h5p!^a!)6y_p2&oln#lsz6x61=wyusg4('
import os
import django
django.setup()
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ROOT_URLCONF = 'producthunt.urls'
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'compressor',
'django.contrib.sites',
'django_comments',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap4',
'producthunt',
'links',
'registration',
]
# Login/out settings - plus import above
from django.urls import reverse
LOGIN_URL=reverse('login')
LOGIN_REDIRECT_URL = reverse('home')
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'producthunt.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
SITE_ID = 1
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
COMPRESS_ENABLED = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = 'static'
MEDIA_ROOT = 'media'
MEDIA_URL = '/media/'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'compressor.finders.CompressorFinder',
)
COMPRESS_PRECOMPILERS = (
('text/x-scss', 'django_libsass.SassCompiler'),
)
urls.py:
"""producthunt URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth import views as auth_views
from links.views import LinkListView
from links.views import UserProfileDetailView
from django.contrib.auth.decorators import login_required as auth # Keep non-users out
from links.views import UserProfileEditView
from links.views import LinkCreateView, LinkDetailView
from links.views import LinkEditView
from links.views import LinkDeleteView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', LinkListView.as_view(), name='home'),
url(r'^login/$', auth_views.login, name='login'),
url(r'^logout/$', auth_views.logout, name='logout'),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^users/(?P<slug>\w+)/$', UserProfileDetailView.as_view(),name='profile'),
url(r'^edit_profile/$', auth(UserProfileEditView.as_view()), name='edit_profile'),
url(r'^link/submit/$', auth(LinkCreateView.as_view()), name='link_submit'),
url(r'^link/(?P<pk>\d+)/$', LinkDetailView.as_view(), name='link_detail'),
url(r'^link/edit/(?P<pk>\d+)/$', auth(LinkEditView.as_view()), name='link_edit'),
url(r'^link/delete/(?P<pk>\d+)/$', auth(LinkDeleteView.as_view()), name='link_delete'),
url(r'^comments/', include('django_comments.urls')),
]
Full terminal output:
(producthunt) ubuntu#ubuntu-VirtualBox:~/Documents/Github/producthunt$ python manage.py runserver
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 325, in execute
settings.INSTALLED_APPS
File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 79, in __getattr__
self._setup(name)
File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 66, in _setup
self._wrapped = Settings(settings_module)
File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 157, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/ubuntu/Documents/Github/producthunt/producthunt/settings.py", line 53, in <module>
LOGIN_URL=reverse('login')
File "/usr/local/lib/python3.6/dist-packages/django/urls/base.py", line 30, in reverse
resolver = get_resolver(urlconf)
File "/usr/local/lib/python3.6/dist-packages/django/urls/resolvers.py", line 68, in get_resolver
urlconf = settings.ROOT_URLCONF
File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 80, in __getattr__
val = getattr(self._wrapped, name)
AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF'
SOLVED. There were a few things wrong. Since upgrading the django install from like 1.10 to 2.2, there were a lot of changes. Including URL referencing (ie. django.conf.urls vs django.urls) and having to re-run requirements.txt to make sure everything was installed and updated correctly.
Related
My settings.py file:
"""
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 2.2.13.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'af^zgg5*t&h)3dghcvd#9o1#st9b(bgh#5a32%m%!g38u(tl!f'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'chat',
'channels',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'myproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# WSGI_APPLICATION = 'myproject.wsgi.application'
ASGI_APPLICATION = 'asgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
And my asgi.py:
"""
ASGI config for myproject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = ProtocolTypeRouter({
'http': get_asgi_application()
})
Error:
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
June 02, 2022 - 07:12:02
Django version 3.0, using settings 'myproject.settings'
Starting ASGI/Channels version 3.0.4 development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\routing.py", line 28, in get_default_application
module = importlib.import_module(path)
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'asgi'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\management\commands\runserver.py", line 107, in inner_run
application=self.get_application(options),
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\manag
unserver.py", line 132, in get_application
return StaticFilesWrapper(get_default_application())
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\routi
in get_default_application
raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'asgi'
i have updated my django from 2.2 to 3.0 but the problem don't go please do something
and the asgi.py file was created by me
just want the server to recognize the routing application and start working
I've followed the channels 2 tutorial, but I'm getting this error after runningI've followed the channels 2 tutorial, but I'm getting this error after runningI've followed the channels 2 tutorial, but I'm getting this error after running
# WSGI_APPLICATION = 'myproject.wsgi.application'
ASGI_APPLICATION = 'asgi.application'
Note how the WSGI example also has the project name? I suspect you need to include projectname in the setting, eg,
ASGI_APPLICATION = 'projectname.asgi.application'
The channels docs seems to support this format (https://channels.readthedocs.io/en/stable/installation.html)
I am creating a web application using django_plotly_dash, a module combining Django, Plotly, and Dash into one package. I am running into an issue where when I try to work with the manage.py file to run commands, I get the error ModuleNotFoundError: No module named 'django_plotly_dash'
From research and the traceback, it seems to problem lies either in my settings.py file specifically with static files/bootstrapping or in my directory structure. Does anybody with more experience with this see any issues in my structures or settings.py that are causing this error
Here is the Traceback message:
Traceback (most recent call last):
File "C:\Users\mvela\Documents\Internships\Contracts\Greene\July Contract\web_app\report_app\manage.py", line 22, in <module>
main()
File "C:\Users\mvela\Documents\Internships\Contracts\Greene\July Contract\web_app\report_app\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\mvela\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\mvela\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\__init__.py", line 395, in execute
django.setup()
File "C:\Users\mvela\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\__init__.py", line
24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\mvela\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\apps\registry.py",
line 91, in populate
app_config = AppConfig.create(entry)
File "C:\Users\mvela\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\apps\config.py", line 212, in create
mod = import_module(mod_path)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\lib\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 "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked
228, in _call_with_frames_removed 228, in _call_with_frames_r
File "<frozen importlib._bootstrap>", line
1030, in _gcd_import 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line nd_and_load
1007, in _find_and_load 1007, in _fid_and_load_unlo
File "<frozen importlib._bootstrap>", line
984, in _find_and_load_unlocked 984, in _fin
ModuleNotFoundError: No module named 'django_plotly_dash'
Here is my directory:
the first level report_app is the main project while the second level home and report_app are django apps within the main project.
and here is my settings.py:
"""
Django settings for report_app project.
Generated by 'django-admin startproject' using Django 3.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-8do=a0m+%$#t^57z4$e6$^13t=5ys1dk29j#21$f_+9=%83d2v'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_plotly_dash.apps.DjangoPlotlyDashConfig',
'home.apps.HomeConfig',
'channels',
'channels_redis'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django_plotly_dash.middleware.BaseMiddleware',
'django_plotly_dash.middleware.ExternalRedirectionMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'report_app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'report_app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
CRISPY_TEMPLATE_PACK = 'bootstrap4'
ASGI_APPLICATION = 'report_app.routing.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis,core,RedisChannelLayer',
'CONFIG': {
'hosts': [('127.0.0.1', 6379)]
}
}
}
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django_plotly_dash.finders.DashAssetFinder',
'django_plotly_dash.finders.DashComponentFinder',
'django_plotly_dash.finders.DashAppDirectoryFinder'
]
PLOTLY_COMPONENTS = [
'dash_core_components',
'dash_html_components',
'dash_renderer',
'dpd_components',
'dash_bootstrap_components'
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATICFILES_LOCATION = 'static'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_FILES_DIR = [
os.path.join(BASE_DIR, 'report_app/static')
]
X_FRAME_OPTIONS = 'SAMEORIGIN'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
If it helps, I was following the following tutorial on using this package:
https://www.youtube.com/watch?v=psvU4zwO3Ao
Please let me know if any further info will help with solving this.
After tinkering, it seems like #yagus was right. I created a new virtualenv and redid the pip installations and now it works. I must have set it up wrong the first time. Thanks for the help #yagus
Hello everyone I am trying to build a website with django that gets info from the form and makes api calls using those parameters.
I am very newby on django and I build a model for this but i cannot import this model it says
-------->>>>>>python manage.py runserver
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\berat.berkol\anaconda3\lib\threading.py", line 926, in _bootstrap_inner
self.run()
File "C:\Users\berat.berkol\anaconda3\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run
autoreload.raise_last_exception()
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception
raise _exception[1]
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\management\__init__.py", line 357, in execute
autoreload.check_errors(django.setup)()
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\apps\registry.py", line 114, in populate
app_config.import_models()
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\apps\config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\berat.berkol\anaconda3\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\berat.berkol\SystemConsole\userUpdate\models.py", line 3, in <module>
from . import views
File "C:\Users\berat.berkol\SystemConsole\userUpdate\views.py", line 13, in <module>
from userUpdate.forms import userPassResetForm
File "C:\Users\berat.berkol\SystemConsole\userUpdate\forms.py", line 2, in <module>
from userUpdate.models import passUser
ImportError: cannot import name 'passUser' from 'userUpdate.models' (C:\Users\berat.berkol\SystemConsole\userUpdate\models.py)
on Windows cmd. I tried this without making a model but if I don't use models i can't render the form to the template.
Here is my home.html
<div class="u-form u-form-1">
<form action="{% url 'userPassreset' %}" method="post" class="u-clearfix u-form-spacing-15 u-form-vertical u-inner-form" style="padding: 15px;" source="custom" name="send">
{% csrf_token %}
<div class="u-form-group u-form-name u-form-group-1">
{{form.as_p}}
{{form.username}}
</div>
<div class="u-align-right u-form-group u-form-submit u-form-group-6">
<input type="submit" value="Sadece Mesaj Gönder" class="u-active-white u-border-0 u-border-radius-10 u-btn u-btn-round u-btn-submit u-button-style u-palette-2-base u-btn-1" name="sendmessage">
</div>
</form>
</div>
urls.py (App)
from django.urls import path, re_path
from django.contrib.auth.views import LoginView
from . import views
app_name='userUpdate'
urlpatterns = [
path('', views.userUpdate, name='home'),
path('login/',
LoginView.as_view(
template_name='login.html'),
name="login"),
path('userPassreset',views.passResetView.as_view(),name='userPassreset'),]
urls.py (Project)
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from django.contrib.auth.views import LoginView
from django.views.generic.base import TemplateView
app_name='userUpdate'
urlpatterns = [
path('admin/', admin.site.urls),
path('login/',include('django.contrib.auth.urls')),
path('', TemplateView.as_view(template_name='home.html'), name='home'),]
models.py
from django.db import models
from django.contrib.auth.models import User
from . import views
class passUser(models.Model):
username = models.CharField(blank=False,max_length=100)
password = models.CharField(blank=False,max_length=100)
number = models.CharField(blank=False,max_length=100)
message = models.CharField(blank=True,max_length=300)
class Meta:
verbose_name = "passUser"
forms.py
from django import forms
from userUpdate.models import passUser
class userPassResetForm(forms.ModelForm):
class Meta:
model = passUser
fields = "__all__"
views.py
from django.shortcuts import render
from datetime import timedelta
from django.utils import timezone
from django.views.generic import TemplateView
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.urls import reverse
import requests
from userUpdate.forms import userPassResetForm
from django.views import View
#csrf_protect
class passResetView(View):
def get(self,request):
form=userPassResetForm()
return render('home.html')
def post(self,request):
passResetuser=self.model.objects.get(pk=2)
form=userPassResetForm(request.POST,instance=passResetuser)
if form.is_valid():
username=form.cleaned_data('username')
password=form.cleaned_data('password')
number=form.cleaned_data('number')
message=form.cleaned_data('message')
context={'form':form}
return render(request,'home.html',context)
settings.py
import os
from django.urls import reverse_lazy
from django.contrib.messages import constants as message_constants
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
reverse_lazy("accounts:list")
LOGIN_URL = reverse_lazy('registration/login')
LOGIN_REDIRECT_URL = reverse_lazy('home')
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
DEBUG = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
ALLOWED_HOSTS = []
# Application definition
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'compressor.finders.CompressorFinder',
)
INSTALLED_APPS = [
'userUpdate.apps.UserupdateConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'SystemConsole.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
"DIRS": [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'SystemConsole.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = '/home/SystemConsole/static'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
SITE_ID = 1
apps.py
from django.apps import AppConfig
class UserupdateConfig(AppConfig):
name = 'userUpdate'
Thank you for your help for now.
And Here is the directory tree :
It's solved by dropping "from . import views" from models. Thanks to #blondelg in comments
Having a hard time understanding why I am receiving this error. If I just leave the api/user/ path it works fine but when I try to add api/user/date_counter/ path I get this error. Using Django 3. Any help would be appreciated.
Pseudo-graphics like below is based on how maven shows the output of dependency:tree command.
In my experience it has been easy to read and type. It naturally matches tree-like file structure:
Backend
|
+-- api
| |
| +-- urls.py
| |
| +-- settings.py
|
+-- date_counter
| |
| +-- urls.py
|
+-- user
| |
| +-- urls.py
date_counter/urls.py
from django.urls import path
from date_counter import views
app_name = 'date_counter'
urlpatterns = [
path('date_counter/', views.DateCounterViewSet.as_view(), name='date_counter'),
]
date_counter/views.py
from django.shortcuts import render
from date_counter.models import Date_Counter
from date_counter.serializers import DateCounterSerializer
class DateCounterViewSet(viewsets.ModelViewSet):
queryset = Date_Counter.objects.all()
serializer_class = DateCounterSerializer
date_counter/serializers.py
from date_counter.models import Date_Counter
from rest_framework import serializers
class DateCounterSerializer(serializers.ModelSerializer):
class meta:
model = Date_Counter
fields = ['user', 'date', 'count']
date_counter/models.py
from django.db import models
from user.models import User
class Date_Counter(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(auto_now=True)
count = models.IntegerField(default=0)
api/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/user/', include('user.urls')),
path('api/user/date_counter/', include('date_counter.urls')),
]
user/urls.py
from django.urls import path
from knox.views import LogoutView
from user import views
app_name = 'user'
urlpatterns = [
path('register/', views.RegisterUserView.as_view(), name='register'),
path('login/', views.LoginUserView.as_view(), name='login'),
path('user/', views.UserView.as_view(), name='user'),
path('logout/', LogoutView.as_view(), name='knox_logout'),
path('registersuperuser/', views.RegisterSuperUserView.as_view(), name='register_super_user'),
path('all/', views.AllUsersView.as_view(), name='all'),
]
api/settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'secret'
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'knox',
'user',
'date_counter',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',),
}
ROOT_URLCONF = 'api.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'api.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'user.User'
Stack Trace
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/urls/resolvers.py", line 590, in url_patterns
iter(patterns)
TypeError: 'module' object is not iterable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/management/base.py", line 395, in check
include_deployment_checks=include_deployment_checks,
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/management/base.py", line 382, in _run_checks
return checks.run_checks(**kwargs)
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/urls/resolvers.py", line 407, in check
for pattern in self.url_patterns:
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/urls/resolvers.py", line 597, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'api.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
I think the problem is how you registering your ViewSet to urlpatterns. Try like this:
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('date_counter', views.DateCounterViewSet)
urlpatterns = [
path('', include(router.urls)),
]
More information can be found in documentation.
Found the issue, the date_counter/views.py file was missing an import from django rest framework, from rest_framework import viewsets.
I have searched online for other solutions with little luck. Posting here is a last resort.
Everything was working well with my Django project. Then suddenly it stopped running the server as it used to. I'm not sure at all what I have done wrong.
The issue is persistent across all of the git branches (it wasn't like this before) - making it even more confusing as the problem is not isolated to my branch only.
Here is the error traceback:
WARNINGS:
?: (1_7.W001) MIDDLEWARE_CLASSES is not set.
HINT: Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middleware.AuthenticationMiddleware, and django.contrib.messages.middleware.MessageMiddleware were removed from the defaults. If your project needs these middleware then you should configure this setting.
System check identified 1 issue (0 silenced).
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001A7227EB598>
Traceback (most recent call last):
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\utils\autoreload.py", line 229, in wrapper
fn(*args, **kwargs)
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\core\management\commands\runserver.py", line 116, in inner_run
self.check_migrations()
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\core\management\commands\runserver.py", line 168, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\db\migrations\executor.py", line 19, in __init__
self.loader = MigrationLoader(self.connection)
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\db\migrations\loader.py", line 47, in __init__
self.build_graph()
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\db\migrations\loader.py", line 185, in build_graph
self.load_disk()
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\site-packages\django\db\migrations\loader.py", line 103, in load_disk
migration_module = import_module("%s.%s" % (module_name, migration_name))
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\venv\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\connect_therapy\migrations\0021_auto_20180313_1946.py", line 4, in <module>
import django.contrib.auth.base_user
ModuleNotFoundError: No module named 'django.contrib.auth.base_user'
Also, note that I tried changing to MIDDLEWARE_CLASSES [...] in settings.py - but it didnt help.
Here is settings.py:
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.11.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'key'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True # should be true unless doing test on local network
ALLOWED_HOSTS = ['*'] # should be [] unless doing test on local network (then it should be ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'co.apps.CTherapyConfig',
"sslserver",
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# This must be changed for production
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
TWILIO_PHONE_NUMBER = '+number'
TWILIO_ACC_SID = 'key'
TWILIO_AUTH_TOKEN = 'token'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
Any ideas/suggestions are welcome.
Just to reiterate. This came out of the blue. No idea what caused it.
Thank you.
It came out because something changed in your project and a migration now fails.
In the error log you can see
File "C:\Users\ASUS\PycharmProjects\5CCS2SEG_Major\connect_therapy\migrations\0021_auto_20180313_1946.py", line 4, in <module>
import django.contrib.auth.base_user
ModuleNotFoundError: No module named 'django.contrib.auth.base_user'
What that migration does? Is still valid or the project is changed and the migration try to load resources that are not anymore available?
If you run python manage.py shell are you able to import from 'django.contrib.auth.base_user'? The problem seems to be in that migration
The 'solution' at the end was to just make a new virtual environment. For some reason the old one messed up.