I am trying to use cloudinary to store my media and static files for my django project. I am using django-cloudinary-storage package from here. First I changed my settings so that media files are stored on cloudinary and pushed it to heroku and it worked fine except the staticfiles were not loading. So I changed my settings again so that static files are also stored in cloudinary. It works fine locally with DEBUG=False. When I see the page source of my html locally, it is getting the css and javascript files from cloudinary. So, then I tried pushing it to heroku using git push heroku master. But I get the below error in my heroku logs:
Step 11/14 : RUN python manage.py collectstatic --noinput
---> Running in 5b062a8f7c52
Traceback (most recent call last):
File "/usr/src/app/manage.py", line 22, in <module>
main()
File "/usr/src/app/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 373, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 417, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 161, in handle
if self.is_local_storage() and self.storage.location:
File "/usr/local/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 215, in is_local_storage
return isinstance(self.storage, FileSystemStorage)
File "/usr/local/lib/python3.10/site-packages/django/utils/functional.py", line 248, in inner
self._setup()
File "/usr/local/lib/python3.10/site-packages/django/contrib/staticfiles/storage.py", line 465, in _setup
self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)()
File "/usr/local/lib/python3.10/site-packages/cloudinary_storage/storage.py", line 275, in __init__
super(HashCloudinaryMixin, self).__init__(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/contrib/staticfiles/storage.py", line 400, in __init__
self.hashed_files = self.load_manifest()
File "/usr/local/lib/python3.10/site-packages/django/contrib/staticfiles/storage.py", line 410, in load_manifest
content = self.read_manifest()
File "/usr/local/lib/python3.10/site-packages/cloudinary_storage/storage.py", line 319, in read_manifest
with self.manifest_storage.open(self.manifest_name) as manifest:
File "/usr/local/lib/python3.10/site-packages/django/core/files/storage.py", line 38, in open
return self._open(name, mode)
File "/usr/local/lib/python3.10/site-packages/cloudinary_storage/storage.py", line 47, in _open
url = self._get_url(name)
File "/usr/local/lib/python3.10/site-packages/cloudinary_storage/storage.py", line 78, in _get_url
return cloudinary_resource.url
File "/usr/local/lib/python3.10/site-packages/cloudinary/__init__.py", line 305, in url
return self.build_url(**self.url_options)
File "/usr/local/lib/python3.10/site-packages/cloudinary/__init__.py", line 315, in build_url
return self.__build_url(**options)[0]
File "/usr/local/lib/python3.10/site-packages/cloudinary/__init__.py", line 312, in __build_url
return utils.cloudinary_url(public_id, **combined_options)
File "/usr/local/lib/python3.10/site-packages/cloudinary/utils.py", line 736, in cloudinary_url
raise ValueError("Must supply cloud_name in tag or in configuration")
ValueError: Must supply cloud_name in tag or in configuration
The command '/bin/sh -c python manage.py collectstatic --noinput' returned a non-zero code: 1
I already have CLOUD_NAME, API_KEY and API_SECRET as environment variables on heroku.
It also shows The command '/bin/sh -c python manage.py collectstatic --noinput' returned a non-zero code: 1 which is in my DockerFile:
FROM python:3.10
# setting work directory
WORKDIR /usr/src/app
# env variables
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWEITEBYTECODE 1
ENV DEBUG 0
# install psycopg dependencies
RUN apt-get update && apt-get install -y \
build-essential \
libpq-dev \
&& rm -rf /var/lib/apt/lists/*
# install dependencies
RUN pip install --upgrade pip
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
RUN python manage.py collectstatic --noinput
RUN adduser -u 99 myuser
USER myuser
CMD gunicorn ramrobazar.wsgi:application --bind 0.0.0.0:$PORT
And here's my settings.py:
INSTALLED_APPS = [
'phonenumber_field',
'ramrobazar.account.apps.AccountConfig',
'ramrobazar.dashboard.apps.DashboardConfig',
'ramrobazar.inventory.apps.InventoryConfig',
'ramrobazar.drf.apps.DrfConfig',
'ramrobazar.demo.apps.DemoConfig',
'mptt',
'rest_framework',
'rest_framework.authtoken',
'rest_framework_simplejwt.token_blacklist',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'cloudinary_storage',
'django.contrib.staticfiles',
'cloudinary',
'corsheaders',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'corsheaders.middleware.CorsMiddleware',
'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',
]
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage'
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
CLOUDINARY_STORAGE = {
'CLOUD_NAME': os.environ.get('CLOUD_NAME'),
'API_KEY': os.environ.get('API_KEY'),
'API_SECRET': os.environ.get('API_SECRET'),
}
DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'
This is my first time using heroku and cloudinary. If anyone has any idea about what the problem might be, please share it. If any more information is required, please ask.
Related
I am trying to set up robot framework on django application. I am testing on a skeleton applciation. Following these instructions https://github.com/kitconcept/robotframework-djangolibrary i get error
% robot tests/test.robot
[ ERROR ] Error in file '/Users/user/hci/pipeline/app/tests/test.robot' on line 13: Importing library 'MIDDLEWARE_CLASSES' failed: ModuleNotFoundError: No module named 'MIDDLEWARE_CLASSES'
Traceback (most recent call last):
None
PYTHONPATH:
/Users/user/.pyenv/versions/3.7.2/bin
/Users/user/.pyenv/versions/3.7.2/lib/python37.zip
/Users/user/.pyenv/versions/3.7.2/lib/python3.7
/Users/user/.pyenv/versions/3.7.2/lib/python3.7/lib-dynload
/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages
==============================================================================
Test :: Django Robot Tests
==============================================================================
Scenario: As a visitor I can visit the django default page | FAIL |
Parent suite setup failed:
No keyword with name 'Start Django' found.
------------------------------------------------------------------------------
Test :: Django Robot Tests | FAIL |
Suite setup failed:
No keyword with name 'Start Django' found.
Also suite teardown failed:
No keyword with name 'Stop Django' found.
1 test, 0 passed, 1 failed
==============================================================================
Output: /Users/user/hci/pipeline/app/output.xml
Log: /Users/user/hci/pipeline/app/log.html
Report: /Users/user/hci/pipeline/app/report.html
This is the content of my files
In settings.py I have
"""
Django settings for pipeline project.
Generated by 'django-admin startproject' using Django 3.2.3.
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/
"""
import os
from pathlib import Path
# 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-pn)5iu$yix_%r9&t$=ww=3t8ttaxt=qymg#u^4-q#((u_v#'
# 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',
'demo',
'django_jenkins',
]
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',
'DjangoLibrary.middleware.AutologinAuthenticationMiddleware',
'DjangoLibrary.middleware.FactoryBoyMiddleware',
'DjangoLibrary.middleware.QuerySetMiddleware',
]
MIDDLEWARE_CLASSES = (
'django.contrib.auth.middleware.AuthenticationMiddleware',
'DjangoLibrary.middleware.AutologinAuthenticationMiddleware',
'DjangoLibrary.middleware.FactoryBoyMiddleware',
'DjangoLibrary.middleware.QuerySetMiddleware',
)
ROOT_URLCONF = 'pipeline.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 = 'pipeline.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
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
In test.robot i have
*** Variables ***
${HOSTNAME} 127.0.0.1
${PORT} 55001
${SERVER} http://${HOSTNAME}:${PORT}/
${BROWSER} firefox
*** Settings ***
Documentation Django Robot Tests
Library Selenium2Library timeout=10 implicit_wait=0
Library MIDDLEWARE_CLASSES ${HOSTNAME} ${PORT} path=pipeline/pipeline manage=pipeline/manage.py settings=pipeline.settings
Suite Setup Start Django and open Browser
Suite Teardown Stop Django and close Browser
*** Keywords ***
Start Django and open Browser
Start Django
Open Browser ${SERVER} ${BROWSER}
Stop Django and close browser
Close Browser
Stop Django
*** Test Cases ***
Scenario: As a visitor I can visit the django default page
Go To ${SERVER}
Wait until page contains element id=explanation
Page Should Contain It worked!
Page Should Contain Congratulations on your first Django-powered page.
I am using python3.7.2
UPDATE
I have updated it but now i get this error
% robot tests/test.robot
==============================================================================
Test :: Django Robot Tests
==============================================================================
Traceback (most recent call last):
File "/Users/user/hci/pipeline/app/manage.py", line 22, in <module>
main()
File "/Users/user/hci/pipeline/app/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/base.py", line 341, in run_from_argv
connections.close_all()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/utils.py", line 230, in close_all
connection.close()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 261, in close
if not self.is_in_memory_db():
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 380, in is_in_memory_db
return self.creation.is_in_memory_db(self.settings_dict['NAME'])
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db
return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'PosixPath' is not iterable
No changes detected
Traceback (most recent call last):
File "/Users/user/hci/pipeline/app/manage.py", line 22, in <module>
main()
File "/Users/user/hci/pipeline/app/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/base.py", line 341, in run_from_argv
connections.close_all()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/utils.py", line 230, in close_all
connection.close()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 261, in close
if not self.is_in_memory_db():
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 380, in is_in_memory_db
return self.creation.is_in_memory_db(self.settings_dict['NAME'])
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db
return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'PosixPath' is not iterable
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
No migrations to apply.
Traceback (most recent call last):
File "/Users/user/hci/pipeline/app/manage.py", line 22, in <module>
main()
File "/Users/user/hci/pipeline/app/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/core/management/base.py", line 341, in run_from_argv
connections.close_all()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/utils.py", line 230, in close_all
connection.close()
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 261, in close
if not self.is_in_memory_db():
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 380, in is_in_memory_db
return self.creation.is_in_memory_db(self.settings_dict['NAME'])
File "/Users/user/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db
return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'PosixPath' is not iterable
------------------------------------------------------------------------------
Django started (PID: 51422)
------------------------------------------------------------------------------
Scenario: As a visitor I can visit the django default page | FAIL |
Parent suite setup failed:
WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
------------------------------------------------------------------------------
Django stopped (PID: 51422)
------------------------------------------------------------------------------
Test :: Django Robot Tests | FAIL |
Suite setup failed:
WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
1 test, 0 passed, 1 failed
==============================================================================
Output: /Users/user/hci/pipeline/app/output.xml
Log: /Users/user/hci/pipeline/app/log.html
Report: /Users/user/hci/pipeline/app/report.html
I'm getting a very strange error that got me really stuck for many hours now.
I did my deploy with Heroku for the first time and am using S3 for Media files. First thing I noticed was that I never had a migration working successfully after installing boto and django-storages-redux, not sure why. Anyway I kept going.
My configurations seemed to be working in AWS, since my staticfiles did go to my bucket the first time I tried it, but I got some img files not coming through, so I decided to reinstall boto and django-registration-redux (to see if it would migrate properly).
In the end it never migrated as expected and now I'm getting the following error:
UnboundLocalError: local variable 'region_name' referenced before assignment
in my BOTO package when collectstatic.
I don't understand why migrate won't work and why I started to get this error when I re-installed boto and django-storages-redux.
terminal:
You have requested to collect static files at the destination
location as specified in your settings.
This will overwrite existing files!
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: yes
Traceback (most recent call last):
File "/Users/Alex/Desktop/Allugare/src/manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute
output = self.handle(*args, **options)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 193, in handle
collected = self.collect()
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 124, in collect
handler(path, prefixed_path, storage)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 349, in copy_file
if not self.delete_file(path, prefixed_path, source_storage):
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 255, in delete_file
if self.storage.exists(prefixed_path):
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/storages/backends/s3boto.py", line 439, in exists
if self.entries:
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/storages/backends/s3boto.py", line 302, in entries
for entry in self.bucket.list(prefix=self.location))
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/storages/backends/s3boto.py", line 301, in <genexpr>
self._entries = dict((self._decode_name(entry.key), entry)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/s3/bucketlistresultset.py", line 34, in bucket_lister
encoding_type=encoding_type)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/s3/bucket.py", line 473, in get_all_keys
'', headers, **params)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/s3/bucket.py", line 399, in _get_all
query_args=query_args)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/s3/connection.py", line 668, in make_request
retry_handler=retry_handler
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/connection.py", line 1071, in make_request
retry_handler=retry_handler)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/connection.py", line 927, in _mexe
request.authorize(connection=self)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/connection.py", line 377, in authorize
connection._auth_handler.add_auth(self, **kwargs)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/auth.py", line 755, in add_auth
**kwargs)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/auth.py", line 574, in add_auth
string_to_sign = self.string_to_sign(req, canonical_request)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/auth.py", line 514, in string_to_sign
sts.append(self.credential_scope(http_request))
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/auth.py", line 496, in credential_scope
region_name = self.determine_region_name(http_request.host)
File "/Users/Alex/Desktop/allugare/lib/python3.5/site-packages/boto/auth.py", line 690, in determine_region_name
return region_name
UnboundLocalError: local variable 'region_name' referenced before assignment
settings.py:
...
INSTALLED_APPS = (
#DJANGO APPS
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
#THIRD PARTY APPS
'allauth',
'allauth.account',
'allauth.socialaccount',
#Social Authentications
'allauth.socialaccount.providers.facebook',
# 'allauth.socialaccount.providers.instagram',
# 'allauth.socialaccount.providers.twitter',
'crispy_forms',
'django_messages',
'storages',
#MY APPS
'lares',
'mensagens',
'profiles',
)
...
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static-live", "static")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "static-live", "media")
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
AWS_ACCESS_KEY_ID = "***"
AWS_SECRET_ACCESS_KEY = "***"
AWS_FILE_EXPIRE = 200
AWS_PRELOAD_METADATA = True
AWS_QUERYSTRING_AUTH = True
DEFAULT_FILE_STORAGE = 'allugare.utils.MediaRootS3BotoStorage'
STATICFILES_STORAGE = 'allugare.utils.StaticRootS3BotoStorage'
# DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
# STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
AWS_STORAGE_BUCKET_NAME = 's3allugare'
S3DIRECT_REGION = 'sa-east-1'
S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME
MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME
MEDIA_ROOT = MEDIA_URL
STATIC_URL = S3_URL + 'static/'
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
AWS_S3_HOST = 'sa-east-1.amazonaws.com'
import datetime
two_months = datetime.timedelta(days=61)
date_two_months_later = datetime.date.today() + two_months
expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT")
AWS_HEADERS = {
'Expires': expires,
'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()), ),
}
wsgi.py
"""
WSGI config for allugare 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/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "allugare.settings")
application = get_wsgi_application()
utils.py
from storages.backends.s3boto import S3BotoStorage
StaticRootS3BotoStorage = lambda: S3BotoStorage(location='static') # S3 bucket name -> static
MediaRootS3BotoStorage = lambda: S3BotoStorage(location='media') # S3 bucket name -> static
Okay, here's the thing, if you're not using the default region of AWS you have to be careful when updating your region, since the S3's has different formats depending on the region.
I'm in South America, thus I'm using sa-east-1 (for São Paulo).
To me it worked when I changed the setting:
AWS_S3_HOST = 'sa-east-1.amazonaws.com'
to
AWS_S3_HOST = 's3-sa-east-1.amazonaws.com'
Enjoy!
I am doing the tango with django tutorial. I am up to chapter 5 on working with models and I am setting up the admin website. I get this strange error:
ImportError: cannot import name get_permission_codename
This seems to go away when I remove the
admin.autodiscover()
from my project/urls.py. But I am concerned that I will need this down the road.
Here is the Traceback I get when I run the development server:
Environment:
Request Method: GET Request URL: http://127.0.0.1:8000/admin/
Django Version: 1.5.4 Python Version: 2.7.3 Installed Applications:
('django.contrib.auth', 'django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.sites',
'django.contrib.messages', 'django.contrib.staticfiles',
'django.contrib.admin', 'rango') Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback: File
"/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py"
in get_response
103. resolver_match = resolver.resolve(request.path_info) File
"/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py"
in resolve
319. for pattern in self.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py"
in url_patterns
347. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File
"/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py"
in urlconf_module
342. self._urlconf_module = import_module(self.urlconf_name) File
"/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py" in
import_module
35. import(name) File "/home/gpanterov/MyProjects/django/tango_with_django_project/tango_with_django_project/urls.py"
in
6. admin.autodiscover() File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/init.py"
in autodiscover
29. import_module('%s.admin' % app) File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py" in
import_module
35. import(name) File "/usr/local/lib/python2.7/dist-packages/django/contrib/contenttypes/admin.py"
in
5. from django.contrib.admin.checks import InlineModelAdminChecks File
"/usr/local/lib/python2.7/dist-packages/django/contrib/admin/checks.py"
in
6. from django.contrib.admin.utils import get_fields_from_path, NotRelationField, flatten File
"/usr/local/lib/python2.7/dist-packages/django/contrib/admin/utils.py"
in
6. from django.contrib.auth import get_permission_codename
Exception Type: ImportError at /admin/ Exception Value: cannot import
name get_permission_codename
When I remove the admin.autodiscover() line, the development server runs and I am able to get to the admin panel, but when I log in with the superuser password I created earlier, I get the message "You don't have permission to edit anything." and I don't see any of the categories I created.
I got this error when downgrading django from latest version (1.8) to an old version (1.4) for testing.
The problem here is that git doesn't delete .pyc files when switching branches (because they are .gitignore'ed) and python only regenerates them when the corresponding .py file is newer than the .pyc file (see this question for details).
The solution is to delete all *.pyc files in django/contrib/admin and django/contrib/contenttypes directories.
cannot import name get_permission_codename
Make sure u have not install all the version of django in your system.
if there then remove all and install fresh django
I installed and configured debug_toolbar as the instruction say.See Here, i could even run syncdb.But when i access the admin page i get this error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 283, in run
self.result = application(self.environ, self.start_response)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/staticfiles/handlers.py", line 68, in __call__
return self.application(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 250, in __call__
self.load_middleware()
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 47, in load_middleware
raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
ImproperlyConfigured: Error importing middleware debug_toolbar.middleware: "No module named toolbar.loader"
And I can't access any other page.Same error.
I searched for a while and couldn't find any answer.What i did wrong here?
I will support the installation of debug_toolbar when you are inside on Virtualenv. Just make sure that its is activated in your settings.py and then do a :
pip install django-debug-toolbar
Do you have the latest version of debug toolbar?
In debug_toolbar/middleware.py the import (line 14) reads:
from debug_toolbar.toolbar.loader import DebugToolbar
See if that matches your debug_toolbar/middleware.py to start with.
It sounds like something is funky with your installation. Check that the directories are alright, and try importing the middleware from ./manage.py shell.
Then perhaps try deleting the debug_toolbar directories manually and reinstalling it with pip if all else fails.
If you are using virtualenv, make sure that you have the virtualenv activated where you have installed debug_toolbar.
http://django-debug-toolbar.readthedocs.org/en/1.2/configuration.html
'debug_toolbar' -> INSTALLED_APPS
'debug_toolbar.middleware.DebugToolbarMiddleware' -> MIDDLEWARE_CLASSES (at first position)
define STATIC_ROOT and ./manage.py collectstatic
DEBUG_TOOLBAR_PATCH_SETTINGS = False
INTERNAL_IPS = ('127.0.0.1',)
I'm having some trouble getting django to play nice with image uploads. My script will create directories based on the date like so:
file = models.FileField(upload_to='uploads/%m-%Y/')
Now, if I create the dated directory in the uploads folder and chmod the folder to 755, the upload works fine, but if I try to chmod the uploads folder without creating the dated sub folder (which I need django to do), I am getting a permissions error.
How do I make it so a folder will allow the creation of sub folders?
Here is a traceback:
Django Version: 1.3
Python Version: 2.5.2
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.admin',
'tagging',
'mediamanager',
'livesettings',
'projects']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
Traceback:
File "/var/lib/python-support/python2.5/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/var/lib/python-support/python2.5/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/var/lib/python-support/python2.5/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/var/www/enigma-dev/enigma/mediamanager/views.py" in upload_media
24. m.upload_media(data=form.cleaned_data, params=params)
File "/var/www/enigma-dev/enigma/mediamanager/models.py" in upload_media
63. self.save()
File "/var/lib/python-support/python2.5/django/db/models/base.py" in save
460. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/var/lib/python-support/python2.5/django/db/models/base.py" in save_base
543. for f in meta.local_fields if not isinstance(f, AutoField)]
File "/var/lib/python-support/python2.5/django/db/models/fields/files.py" in pre_save
255. file.save(file.name, file, save=False)
File "/var/lib/python-support/python2.5/django/db/models/fields/files.py" in save
92. self.name = self.storage.save(name, content)
File "/var/lib/python-support/python2.5/django/core/files/storage.py" in save
49. name = self._save(name, content)
File "/var/lib/python-support/python2.5/django/core/files/storage.py" in _save
166. os.makedirs(directory)
File "/usr/lib/python2.5/os.py" in makedirs
171. mkdir(name, mode)
Exception Type: OSError at /media-manager/upload/
Exception Value: [Errno 13] Permission denied: '/var/www/site-dev/site/static/uploads/04-2011'
I was getting the same error and fix it by changing:
MEDIA_ROOT = '/media/'
to:
MEDIA_ROOT = 'media/'
Under settings.py.
The process that is running your Python interpreter doesn't have permission to write into the media directory. You'll need to either chgrp or chown the media directory to the same group as your Python process, and ensure you have at least g+rwx on directories and g+rw on files.
For me, I forgot to add: MEDIA_ROOT = os.path.join(BASE_DIR,'media') to my settings.py file on my production server.
Make sure you have done following
Your settings.py
...
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
...
Also set permission to media directory
chgrp -R www-data /path/to/media/
chmod -R g+w /path/to/media/
Thanks to https://stackoverflow.com/users/10949995/clement-tong for the inspiration. I experienced the same error in a production environment and I had to change settings.py file to include a preceding forward slash:
MEDIA_ROOT = os.path.join(BASE_DIR, "/media")
I was getting the same error and fix it by doing the following in setting.py file of the project:
MEDIA_ROOT = '/media/'
to
MEDIA_ROOT = 'media/'