ModuleNotFoundError: No module named 'allauth.accountallauth' - python

I've a app name cz.
Error:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\ashis\PycharmProjects\ChatZone\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\ashis\PycharmProjects\ChatZone\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute
django.setup()
File "C:\Users\ashis\PycharmProjects\ChatZone\venv\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\ashis\PycharmProjects\ChatZone\venv\lib\site-packages\django\apps\registry.py", line 91, in populate
app_config = AppConfig.create(entry)
File "C:\Users\ashis\PycharmProjects\ChatZone\venv\lib\site-packages\django\apps\config.py", line 116, in create
mod = import_module(mod_path)
File "C:\Users\ashis\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'allauth.accountallauth'
This is my settings.py file:
from pathlib import Path
from django.template.backends import django
import os
import allauth
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'cz',
'allauth',
'allauth.account'
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
]
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 = 'ChatZone.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 = 'ChatZone.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 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/'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)
SITE_ID = 1
LOGIN_REDIRECT_URL = '/'
SOCIALACCOUNT_PROVIDERS = {
'google': {
'SCOPE': [
'profile',
'email',
],
'AUTH_PARAMS': {
'access_type': 'online',
}
}
}
My urls.py for the project ChatZone:
from django.contrib import admin
from django.urls import path,include
from django.views.generic import TemplateView
import allauth
urlpatterns = [
path('', TemplateView.as_view(template_name='cz/index.html')),
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')),
path('cz/',include('cz.urls')),
]
I've tried many approach to solve this problem but I don't know how to solve it. I've searched everywhere but I can't find this module in my code. How can I tackle these kinds of problems in the future?

You've missed a comma. Very common typo:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'cz',
'allauth',
'allauth.account' # no comma here
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
]
So you want:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'cz',
'allauth',
'allauth.account', # comma added
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
]

you can specify which version of python your web app uses -3.7, 3.8. choose a python version that you have installed the package, be sure the same.
pip 3.8 install --user allauth
after that create a virtualenv and virtualenv's using the python version and then
pip install allauth

Related

Django standalone apps with one app depending on another app - django.db.migrations.exceptions.NodeNotFoundError

I am using Django 4.0
I have written two standalone apps. Foo and FooBar.
Application Foo uses package django_nyt. Application FooBar uses functionality from application Foo.
I am able to makemigrations and migrate models in application Foo, however, when working with application FooBar, when I attempt to makemigrations, I get the following error trace:
Traceback (most recent call last):
File "manage.py", line 14, in <module>
execute_from_command_line(sys.argv)
File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv
self.execute(*args, **cmd_options)
File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/base.py", line 460, in execute
output = self.handle(*args, **options)
File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/base.py", line 98, in wrapped
res = handle_func(*args, **kwargs)
File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 100, in handle
loader = MigrationLoader(None, ignore_no_migrations=True)
File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/db/migrations/loader.py", line 58, in __init__
self.build_graph()
File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/db/migrations/loader.py", line 276, in build_graph
self.graph.validate_consistency()
File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/db/migrations/graph.py", line 198, in validate_consistency
[n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)]
File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/db/migrations/graph.py", line 198, in <listcomp>
[n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)]
File "/path/to/project/foobar/env/lib/python3.8/site-packages/django/db/migrations/graph.py", line 60, in raise_error
raise NodeNotFoundError(self.error_message, self.key, origin=self.origin)
django.db.migrations.exceptions.NodeNotFoundError: Migration foo.0001_initial dependencies reference nonexistent parent node ('django_nyt', '0010_auto_20220802_2211')
contents of /path/to/proj/foo/env/lib/python3.8/site-packages/django_nyt/migrations/0010_auto_20220802_2211
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('django_nyt', '0009_alter_foo_subscription_and_more'),
]
operations = [
migrations.AlterField(
model_name='notification',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='settings',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='subscription',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
]
Since these are standalone apps, I am using the design pattern advocated for in Django Standalone Reusable Libraries.
common.py (foo application)
from pathlib import Path
from django.conf import settings
SAMPLE_PROJECT_DIR_NAME='sample_project'
BASE_DIR = f"{Path(__file__).parent.resolve()}/{SAMPLE_PROJECT_DIR_NAME}"
STANDALONE_APP_NAME='foo'
STATIC_URL = '/static/'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.messages',
'django.contrib.humanize',
'django.contrib.sites',
'django_nyt.apps.DjangoNytConfig',
STANDALONE_APP_NAME,
'myapp',
]
SECRET_KEY="lskfjklsdfjalkfslfjslfksdjfslkfslkfj"
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
DEBUG=True
# AUTH_USER_MODEL='testdata.CustomUser',
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': f"{BASE_DIR}/db.sqlite3",
},
}
SITE_ID=1
ROOT_URLCONF=f"{SAMPLE_PROJECT_DIR_NAME}.urls"
TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.messages.context_processors.messages',
]
},
},
]
USE_TZ=True
MIDDLEWARE=[
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
]
settings.configure(
SECRET_KEY=SECRET_KEY,
DEFAULT_AUTO_FIELD = DEFAULT_AUTO_FIELD,
DEBUG=DEBUG,
# AUTH_USER_MODEL=AUTH_USER_MODEL,
DATABASES=DATABASES,
SITE_ID=SITE_ID,
ROOT_URLCONF=ROOT_URLCONF,
INSTALLED_APPS=INSTALLED_APPS,
STATIC_URL=STATIC_URL,
TEMPLATES=TEMPLATES,
USE_TZ=USE_TZ,
MIDDLEWARE=MIDDLEWARE,
)
common.py (foobar)
import sys
from pathlib import Path
from django.conf import settings
SAMPLE_PROJECT_DIR_NAME='sample_project'
PARENT_DIR = f"{Path(__file__).parent.parent.resolve()}"
BASE_DIR = f"{Path(__file__).parent.resolve()}/{SAMPLE_PROJECT_DIR_NAME}"
STANDALONE_APP_NAME='foobar'
STATIC_URL = '/static/'
sys.path.insert(0, f"{PARENT_DIR}/django-foo")
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.messages',
'django.contrib.humanize',
'django.contrib.sites',
'django_nyt.apps.DjangoNytConfig',
'foo',
STANDALONE_APP_NAME,
'myapp',
]
SECRET_KEY="lskfjklsdfjalkfslfjslfksdjfslkfslkfj"
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
DEBUG=True
# AUTH_USER_MODEL='testdata.CustomUser',
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': f"{BASE_DIR}/db.sqlite3",
},
}
SITE_ID=1
ROOT_URLCONF=f"{SAMPLE_PROJECT_DIR_NAME}.urls"
TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.messages.context_processors.messages',
]
},
},
]
USE_TZ=True
MIDDLEWARE=[
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
]
FOOBAR_DATA={}
settings.configure(
SECRET_KEY=SECRET_KEY,
DEFAULT_AUTO_FIELD = DEFAULT_AUTO_FIELD,
DEBUG=DEBUG,
# AUTH_USER_MODEL=AUTH_USER_MODEL,
DATABASES=DATABASES,
SITE_ID=SITE_ID,
ROOT_URLCONF=ROOT_URLCONF,
INSTALLED_APPS=INSTALLED_APPS,
STATIC_URL=STATIC_URL,
TEMPLATES=TEMPLATES,
USE_TZ=USE_TZ,
MIDDLEWARE=MIDDLEWARE,
FOOBAR_DATA = FOOBAR_DATA,
)
manage.py (same for both foo and foobar standalone applications)
import os
import sys
import django
from common import *
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), SAMPLE_PROJECT_DIR_NAME))
django.setup()
if __name__ == '__main__':
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
I have looked in the migrations folders for both applications and this is what I found:
foo app has the migration 0010_auto_20220802_2211 generated, and applied to django_nyt, to change the PK auto fields to use BigInteger.
foobar app does not have the migration file 0010_auto_20220802_2211 generated for django_nyt (hence the migration error). I can't for the life of me, work out why foobar is not using the migrations generated by foo, since it has a dependency on foo.
A no-brainer hack would be to simply copy over the missing migration file, but that is too fragile, and I want to actually understand what is going on, and why foobar is not using/applying the migrations created by a dependency.
This is what I have tried so far (did not resolve the issue):
I checked in the migration files for foo. Initially, I had kept them out of the repository
Created a dummy model class in foobar, that explicitly had a dependency on a model in dyango_nyt - the reasoning being that, if a django_nyt model existed in foobar, i would force migrations to be created for django_nyt.
This is what my dummy class in foobar/models.py looked like:
from django_nyt.models import Notification
class FooBarMigrationHack(Notification):
name = models.CharField(max_length=10)
None of the above has worked, and I'm still getting the same error stack trace as shown above, in my question.
How do I resolve this without having to manually copy the 'missing' migration file from foo/migrations/ to foobar/migrations/ ?

how can I avoid getting duplicates: account?

I am trying to install pip3 install django-allauth to prevent login before email confirmation, but at moment when setting up settings.py I get the following error. I don't want to rename all the project names, because it is going to affect the complete project. Is there a way to achieve this without too many changes?
xxxxxx#xxxxxx:~/Documents/blackowl$ python3 manage.py makemigrations account
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/home/xxxxxx/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_com
mand_line
utility.execute()
File "/home/xxxxxx/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute
django.setup()
File "/home/xxxxxx/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/xxxxxx/.local/lib/python3.6/site-packages/django/apps/registry.py", line 95, in populate
"duplicates: %s" % app_config.label)
django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: account
# Application definition
​
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'allauth' ,
'allauth.account' ,
'allauth.socialaccount' ,
'allauth.socialaccount.providers.github' ,
'apps.website',
'apps.account'
]
​
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 = 'blackowl.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',
],
},
},
]
​
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)
Try to add this under INSTALLED_APPS :
'django.contrib.account'

How to fix "AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF'"

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.

ModuleNotFoundError: No module named 'yoursite'

I'm relatively new to both Python and Django, and I've had an app developed by someone else. I'm trying to write a script which automatically opens an SSH Tunnel and runs a command from my local machine to my remote postgres database so that I can do a parse locally - this is normally done from the terminal by typing python manage.py parse. This has worked previously when I have run a manual SSH tunnel but now want to set it up to run in a script and close the connection automatically. My script is currently set as below:
import psycopg2
import sshtunnel
from django.core.management import execute_from_command_line
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='ssh_username', ssh_password='ssh_password',
remote_bind_address=('username2.postgres.pythonanywhere-services.com', port)
) as tunnel:
params = {
"dbname": 'dbname',
"user": 'user',
"password": 'password',
"host": 'host',
"port": tunnel.local_bind_port,
}
connection = psycopg2.connect(**params)
cursor = connection.cursor()
execute_from_command_line(["manage.py", "parse"])
cursor.close
connection.close()
I'm now getting the error below when I run the script (which is located in the root file of my app):
/home/user/anaconda3/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
""")
Traceback (most recent call last):
File "ssh_tunnel.py", line 24, in <module>
execute_from_command_line(["manage.py", "parse"])
File "/home/user/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/home/user/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 307, in execute
settings.INSTALLED_APPS
File "/home/user/anaconda3/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__
self._setup(name)
File "/home/user/anaconda3/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup
self._wrapped = Settings(settings_module)
File "/home/user/anaconda3/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/home/user/anaconda3/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 941, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'yoursite'
It seems to me that it must be an issue where I haven't changed the name of a script somewhere, but having done a search through my system I can't seem to find 'yoursite' in any of my code. Does anyone have any idea where the code might be that this error is referring to?
Settings.py contents:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
DEBUG = True
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api',
'taggit',
'rest_framework',
'taggit_serializer',
'django.contrib.sites',
'rest_framework.authtoken',
'rest_auth',
'allauth',
'allauth.account',
'rest_auth.registration',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.twitter',
'corsheaders',
)
MIDDLEWARE_CLASSES = (
'corsheaders.middleware.CorsMiddleware',
'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',
'django.middleware.security.SecurityMiddleware',
)
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',
'api.context_processors.menubar'
# 'social_django.context_processors.backends',
# 'social_django.context_processors.login_redirect',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
CORS_ORIGIN_ALLOW_ALL = True
DATABASES = {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'username',
'USER': 'user',
'PASSWORD': 'password',
}
}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'HOST': 'xxxxxxxx',
'NAME': 'name',
'USER': 'user',
'PASSWORD': 'password',
}
}
else:
DATABASES['default']['HOST'] = '127.0.0.1'
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_ROOT = 'static/'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'rest_framework.authentication.SessionAuthentication',
"allauth.account.auth_backends.AuthenticationBackend",
)
REST_FRAMEWORK = {
'PAGE_SIZE': 10,
'DEFAULT_AUTHENTICATION_CLASSES': (
'api.permissions.POSTOnlyAuthentication',
),
}
SESSION_SERIALIZER = "django.contrib.sessions.serializers.PickleSerializer"
SITE_ID = 1
AUTH_USER_MODEL = 'api.MyUser'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'app#gmail.com'
EMAIL_HOST_PASSWORD = 'app.development'
EMAIL_PORT = 587
ACCOUNT_EMAIL_VERIFICATION = 'optional'
ACCOUNT_EMAIL_REQUIRED = True
LOGIN_URL = LOGIN_REDIRECT_URL = 'api/auth/login/'
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_USERNAME_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = 'username'
ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = LOGIN_URL
Authorisation details have been changed.
Structure is:
App Root
-requirements.txt
-app.yaml
-manage.py
-ssh_tunnel.py
api
mysite
-__init__.py
-settings.py
-wsgi.py
static

Django 1.10 Translation

I was trying internationalization/localization in django.
I am getting an error while i am trying to make the '.po' files using the command
./manage.py makemessages
relevant parts from settings.py
import os
from django.utils.translation import ugettext_lazy as _
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls.apps.PollsConfig'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'sampleproject.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',
'django.template.context_processors.i18n'
],
},
},
]
WSGI_APPLICATION = 'sampleproject.wsgi.application'
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LANGUAGES = [
('fi-FI', _('Finnish')),
('en', _('English')),
]
LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale'),
]
relevant parts from urls.py
urlpatterns += i18n_patterns(
url(r'^$', home, name='home'),
url(r'^admin/', include(admin.site.urls)),
url(r'^polls/', include('polls.urls')),
)
here is the traceback.
Traceback (most recent call last):
File "./manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/base.py", line 305, in run_from_argv
self.execute(*args, **cmd_options)
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/base.py", line 356, in execute
output = self.handle(*args, **options)
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/commands/makemessages.py", line 361, in handle
potfiles = self.build_potfiles()
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/commands/makemessages.py", line 393, in build_potfiles
self.process_files(file_list)
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/commands/makemessages.py", line 488, in process_files
self.process_locale_dir(locale_dir, files)
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/commands/makemessages.py", line 507, in process_locale_dir
build_file.preprocess()
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/commands/makemessages.py", line 113, in preprocess
content = templatize(src_data, self.path[2:])
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/utils/translation/__init__.py", line 214, in templatize
return _trans.templatize(src, origin)
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/utils/translation/trans_real.py", line 670, in templatize
"%s (%sline %d)" % (t.contents, filemsg, t.lineno)
SyntaxError: Translation blocks must not include other block tags: blocktrans count var|length as count (file htmlcov/_project_Myapps_for_sample_lib_python3_4_site-packages_django_templatetags_i18n_py.html, line 1073)
Dev Setup:
Django 1.10
Python 3.4.5
As this is my first question in SO, pardon me if there's any mistake :)
Thanks in advance :)
The error occurred because of the htmlcov folder which was generated while running the coverage script.
Removed that folder and executed the following commands to generate the '.po' files.
./manage.py makemessages -l fi
and the following command to generate the '.mo' files.
./manage.py compilemessages

Categories