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
Related
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/ ?
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
After trying to upload my django-project to heroku i get the following error, even though I tried to configure setting.py in accordance with heroku documentation. Tried to fix it myself for couple of days but I clearly got no idea about what is wrong.
-----> $ python manage.py collectstatic --noinput
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 "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle
collected = self.collect()
File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 104, in collect
for path, storage in finder.list(self.ignore_patterns):
File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/finders.py", line 130, in list
for path in utils.get_files(storage, ignore_patterns):
File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files
directories, files = storage.listdir(location)
File "/app/.heroku/python/lib/python3.7/site-packages/django/core/files/storage.py", line 316, in listdir
for entry in os.scandir(path):
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_3daca1eccd4631486a8597ada28d44da/static'
! Error while running '$ python manage.py collectstatic --noinput'.
See traceback above for details.
You may need to update application code to resolve this error.
Or, you can disable collectstatic for this application:
$ heroku config:set DISABLE_COLLECTSTATIC=1
https://devcenter.heroku.com/articles/django-assets
! Push rejected, failed to compile Python app.
! Push failed
Here is my django settings.py:
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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '6e71nuw7=a-eow4ywhqfp6f+_7s-y7wo!4scy7xhj2vbem3#)m'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["dyadyanurik-visitka.herokuapp.com/", "127.0.0.1"]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'visitka.apps.VisitkaConfig',
'storages',
]
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.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/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_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY")
AWS_STORAGE_BUCKET_NAME = os.environ.get("AWS_STORAGE_BUCKET_NAME")
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
Any ideas about it?
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 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'