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/'
Related
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 noticed this error while trying to access /admin/. Whenever /admin/model_name or /admin/ or /admin/* is accessed django says OverflowError at /admin/ and regular expression code size limit exceeded. I did a little digging and came across this SO post. I have checked urls.py of app since regex are mostly used in urls. But all I have is a typical admin url, nothing complex.
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
....
]
Stack trace
Environment:
Request Method: GET
Request URL: http://domain/admin/
Django Version: 1.9.8
Python Version: 2.7.6
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'haystack',
'myapp.apps.core',
'myapp.apps.home',
'myapp.apps.accounts',
'myapp.apps.dashboard',
'myapp.apps.app1',
'myapp.apps.app3',
'myapp.apps.app5',
'myapp.apps.app6',
'myapp.apps.app7',
'myapp.apps.app8',
'myapp.apps.app9']
Installed 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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in wrapper
265. return self.admin_view(view, cacheable)(*args, **kwargs)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
244. return view(request, *args, **kwargs)>
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)>
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in index
505. app_list = self.get_app_list(request)>
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in get_app_list
488. app_dict = self._build_app_dict(request)>
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in _build_app_dict
473. current_app=self.name,
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/urlresolvers.py" in reverse
600. return force_text(iri_to_uri(resolver._revers>e_with_prefix(view, prefix, *args, **kwargs)))
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix>
488. if re.search('^%s%s' % (re.escape(_prefix), pattern), candidate_pat % candidate_subs, re.UNICODE):
File "/usr/lib/python2.7/re.py" in search>
142. return _compile(pattern, flags).search(string)
File "/usr/lib/python2.7/re.py" in _compile>
242. p = sre_compile.compile(pattern, flags)
File "/usr/lib/python2.7/sre_compile.py" in compile
521. groupindex, indexgroup
Exception Type: OverflowError at /admin/
Exception Value: regular expression code size limit exceeded
We are using django+apache.
Any help is much appreciated.
TIA
I have managed to solve this by restarting apache2 with
sudo service apache2 restart.
Of course, I have inspected apache2 error log with
sudo tail-f /var/logs/apache2/error.log
But that gave me same output as stack trace. Aforementioned is a work around for this issue. I am not marking this question as solved since real issue have not been found yet.
Thanks.
I am running Django 1.6 framework on CentOS 6.5 (AWS EC2 instance) and serving the website using httpd web server. I am using django-allauth package for user account signup. When one signs up, allauth sends an outbound email to the user and then the user has to confirm their email address by clicking on a link in the email. Here are the corresponding SMTP settings in settings.py:
# smtp server settings for gmail
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'myusername#gmail.com'
EMAIL_HOST_PASSWORD = '<mypassword>'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
On my development server (which is also a CentOS 6.5 on a Virtualbox on my Windows laptop), on which I just run the Django based webserver (using python manage.py runserver), all is well i.e. When I do a registration, it is able to send an outbound email and I am able to successfully register and login subsequently.
But on the test server (AWS EC2 instance running CentOS 6.5 using httpd and using Django 1.6 on it), when I try to register, it ends up in the page throwing a "Permission denied" error, the details of the stack trace which I am pasting below.
error at /accounts/signup/
[Errno 13] Permission denied
Request Method: POST
Request URL: http://<server_ip_address>/accounts/signup/
Django Version: 1.6.2
Exception Type: error
Exception Value:
[Errno 13] Permission denied
Exception Location: /usr/lib64/python2.6/socket.py in create_connection, line 567
Python Executable: /usr/bin/python
Python Version: 2.6.6
Python Path:
['/var/www/html/firstProject',
'/usr/lib64/python26.zip',
'/usr/lib64/python2.6',
'/usr/lib64/python2.6/plat-linux2',
'/usr/lib64/python2.6/lib-tk',
'/usr/lib64/python2.6/lib-old',
'/usr/lib64/python2.6/lib-dynload',
'/usr/lib64/python2.6/site-packages',
'/usr/lib/python2.6/site-packages']
Request Method: POST
Request URL: http://<server_ip_address>/accounts/signup/
Django Version: 1.6.2
Python Version: 2.6.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'print_string',
'CompanyApp',
'UserApp',
'south',
'allauth',
'allauth.account',
'allauth.socialaccount',
'sendgrid',
'django_cleanup')
Installed Middleware:
('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')
Traceback:
File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/lib/python2.6/site-packages/allauth/account/views.py" in dispatch
62. **kwargs)
File "/usr/lib/python2.6/site-packages/allauth/account/views.py" in dispatch
133. **kwargs)
File "/usr/lib/python2.6/site-packages/django/views/generic/base.py" in dispatch
87. return handler(request, *args, **kwargs)
File "/usr/lib/python2.6/site-packages/allauth/account/views.py" in post
78. response = self.form_valid(form)
File "/usr/lib/python2.6/site-packages/allauth/account/views.py" in form_valid
164. self.get_success_url())
File "/usr/lib/python2.6/site-packages/allauth/account/utils.py" in complete_signup
149. signal_kwargs=signal_kwargs)
File "/usr/lib/python2.6/site-packages/allauth/account/utils.py" in perform_login
117. send_email_confirmation(request, user, signup=signup)
File "/usr/lib/python2.6/site-packages/allauth/account/utils.py" in send_email_confirmation
278. signup=signup)
File "/usr/lib/python2.6/site-packages/allauth/account/models.py" in send_confirmation
56. confirmation.send(request, signup=signup)
File "/usr/lib/python2.6/site-packages/allauth/account/models.py" in send
131. ctx)
File "/usr/lib/python2.6/site-packages/allauth/account/adapter.py" in send_mail
93. msg.send()
File "/usr/lib/python2.6/site-packages/django/core/mail/message.py" in send
274. return self.get_connection(fail_silently).send_messages([self])
File "/usr/lib/python2.6/site-packages/django/core/mail/backends/smtp.py" in send_messages
87. new_conn_created = self.open()
File "/usr/lib/python2.6/site-packages/django/core/mail/backends/smtp.py" in open
48. local_hostname=DNS_NAME.get_fqdn())
File "/usr/lib64/python2.6/smtplib.py" in __init__
239. (code, msg) = self.connect(host, port)
File "/usr/lib64/python2.6/smtplib.py" in connect
295. self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib64/python2.6/smtplib.py" in _get_socket
273. return socket.create_connection((port, host), timeout)
File "/usr/lib64/python2.6/socket.py" in create_connection
567. raise error, msg
Exception Type: error at /accounts/signup/
Exception Value: [Errno 13] Permission denied
I am splitting my hair on why on my dev environment (Django on CentOS 6.5 running Django test web server + django-allauth) it works fine, whereas on the AWS EC2 instance running CentOS 6.5 + Django 1.6 + httpd + django-allauth, it ends up in this error. Has the root cause of this error do with the server's inability to send outbound emails? Or is it something else that is the root cause?
Any insights on how to resolve this issue and keep moving forward? I am open for change (including the OS if needed). But any resolution that would need the least changes would be helpful.
Thanks.
I'm trying to diagnose the error in my custom middleware somehow brings down my session middleware.
The custom middleware is a simple app which deletes old files in some folders.
class DeleteMediaMiddleware(object):
time_limit = 100.
def check_folder(self,folder):
'''Deletes the files older than "time_limit" '''
os.chdir(folder)
files_in_folder = os.listdir(os.curdir)
for my_file in files_in_folder:
creation_time = os.path.getmtime(my_file)
file_lifetime = time.time() - creation_time
if file_lifetime > self.time_limit:
os.remove(my_file)
def process_request(self, request):
'''Standard middleware method which runs on every request'''
self.check_folder(config.input_folder)
self.check_folder(config.output_folder)
self.check_folder(config.plot_folder)
self.check_folder(config.report_folder)
return None
It is located in the Django project folder. (The levels is how Django creates by default. In my case the project is named expofit, and the folder structure is expofit/expofit)
project_folder_lvl1/project_folder_lvl2/mymiddleware.py
I added the middleware to Djagno settings:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'server.mymiddleware.DeleteMediaMiddleware',
)
However, i end up with an error.
Exception Value: no such table: django_session
which is from checking a session value in views.py:
....
if request.session.has_key('user_id'):
....
As soon as i disable my middleware in Django settings, everything works normally.
UPDATE:
I sucesfully open the database, which is an sqlite file located in the project_folder_lvl1, and locate the table which isn't accessible.
Here is the complete Django traceback.
Environment:
Request Method: GET
Request URL: http://localhost:8000/expofit/
Django Version: 1.4.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'expofit_django_app',
'south',
'django.contrib.admin')
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',
'server.mymiddleware.DeleteMediaMiddleware')
Traceback:
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
77. return view_func(*args, **kwargs)
File "/home/alan/Desktop/expofit/expofit_hg/py/server/expofit_django_app/views.py" in check
59. return view(request, *args, **kwargs)
File "/home/alan/Desktop/expofit/expofit_hg/py/server/expofit_django_app/views.py" in start
23. if request.session.has_key('user_id'):
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py" in has_key
103. return key in self._session
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py" in _get_session
165. self._session_cache = self.load()
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/contrib/sessions/backends/db.py" in load
19. expire_date__gt=timezone.now()
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/db/models/manager.py" in get
131. return self.get_query_set().get(*args, **kwargs)
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/db/models/query.py" in get
361. num = len(clone)
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/db/models/query.py" in __len__
85. self._result_cache = list(self.iterator())
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/db/models/query.py" in iterator
291. for row in compiler.results_iter():
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in results_iter
763. for rows in self.execute_sql(MULTI):
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
818. cursor.execute(sql, params)
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/db/backends/util.py" in execute
40. return self.cursor.execute(sql, params)
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py" in execute
337. return Database.Cursor.execute(self, query, params)
Exception Type: DatabaseError at /expofit/
Exception Value: no such table: django_session
Looking for ideas on how to debug this problem?
The problem was fixed by adding the absolute path to the sqlite database.
settings.py which yielded the error:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'expofit_database',
...
...
new settings.py:
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join( PROJECT_PATH, 'expofit_database'),
...
...
From what i figured, the problem was in calling the
os.chdir(folder)
inside the check_folder function which messed up the runtime paths.
Although setting the absolute path solved the problem for accessing the database, i removed the os.chdir(folder) to prevent potential errors in the future.
def check_folder(folder):
time_limit = 100.
files_in_folder = os.listdir(folder)
for file_name in files_in_folder:
file_path = os.path.join(folder,file_name)
creation_time = os.path.getmtime(file_path)
file_lifetime = time.time() - creation_time
if file_lifetime > time_limit:
os.remove(file_path)
I currently have a simple model defined, with a photoupload feature using django thumbnails plugin.
but when i try to upload it gives me the following error:
OSError at /admin/products/photo/add/
(13, 'Permission denied')
Now, i know this is seems to be a permission issue, so the first thing i checked were permissions on the directory and changed these to 777 (Just to Test), restarted the server and fcgi and it still gives the error.
Traceback
Traceback: File "/usr/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args,
**callback_kwargs) File "/usr/lib/python2.6/dist-packages/django/contrib/admin/options.py" in wrapper
226. return self.admin_site.admin_view(view)(*args,
**kwargs) File "/usr/lib/python2.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs) File "/usr/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in inner
186. return view(request, *args, **kwargs) File "/usr/lib/python2.6/dist-packages/django/db/transaction.py" in _commit_on_success
240. res = func(*args, **kw) File "/usr/lib/python2.6/dist-packages/django/contrib/admin/options.py" in add_view
734. self.save_model(request, new_object, form, change=False) File "/usr/lib/python2.6/dist-packages/django/contrib/admin/options.py" in save_model
557. obj.save() File "/usr/lib/python2.6/dist-packages/django/db/models/base.py" in save
410. self.save_base(force_insert=force_insert, force_update=force_update) File "/usr/lib/python2.6/dist-packages/django/db/models/base.py" in save_base
483. values = [(f, f.get_db_prep_save(raw and getattr(self, f.attname) or f.pre_save(self, True))) for f in meta.local_fields if not isinstance(f, AutoField)] File "/usr/lib/python2.6/dist-packages/django/db/models/fields/files.py" in pre_save
252. file.save(file.name, file, save=False) File "/var/www/django_projects/gang/../gang/products/thumbs.py" in save
84. super(ImageWithThumbsFieldFile, self).save(name, content, save) File "/usr/lib/python2.6/dist-packages/django/db/models/fields/files.py" in save
91. self.name = self.storage.save(name, content) File "/usr/lib/python2.6/dist-packages/django/core/files/storage.py" in save
47. name = self._save(name, content) File "/usr/lib/python2.6/dist-packages/django/core/files/storage.py" in _save
146. os.makedirs(directory) File "/usr/lib/python2.6/os.py" in makedirs
150. makedirs(head, mode) File "/usr/lib/python2.6/os.py" in makedirs
150. makedirs(head, mode) File "/usr/lib/python2.6/os.py" in makedirs
150. makedirs(head, mode) File "/usr/lib/python2.6/os.py" in makedirs
157. mkdir(name, mode)
Exception Type: OSError at /admin/products/photo/add/ Exception Value: (13, 'Permission denied')
The user that the FCGI daemon is being run on definitely has access to read and write to that directory.
From settings.py
MEDIA_ROOT = '/var/www/sites/gang/http/media/'
MEDIA_ROOT_URL = '/media/'
I just ran into this same problem. And found the solution if you are hosting with Apache as your server. For instance if my settings were:
MEDIA_ROOT = '/var/www/media/geekingreen'
then I would simply need to give that folder the correct permissions recursively to make sure that any sub-folders also have the same permission. The default group for apache is www-data so to give permission to my django app I would run these commands.
cd /var/www/media
chgrp -R www-data geekingreen/
chmod -R g+w geekingreen/
The chgrp -R www-data geekingreen/ command changes the directory geekingreen and any subdirectories to have the group www-data.
The chmod -R g+w geekingreen/ command changes what permissions the group has on all of these folders that now belong to www-data, to now have the write permission. Obviously required for uploads.
Hope this can help anyone that may have had a similar problem.
Try checking the permissions on each directory in the path starting at /. Just a thought.
mkdir(name, mode)
Exception Type: OSError at /admin/products/photo/add/
but your application is deployed at
/var/www/django_projects/gangr/../gangr/
Do you have a directory path set to an absolute path "/admin/products/photo/add/" rather than something relative like "admin/products/photo/add/"?
Check the MEDIA_ROOT and MEDIA_URL in your settings.py file.
http://docs.djangoproject.com/en/dev/ref/settings/#media-root
Just in case you run into this when running your development server.
I ran the development server as root like this: sudo python manage.py runserver 0.0.0.0:80 in order to test the site with an iPad in the same LAN network.
The cache files generated in that session belonged to root. So when I ran the project the next day NOT as root I got the permission denied error.
You had to modify the permissions and owner settings in order for your app to be able to upload media files.
You should run these commands to grant permission to your Django app as the default group for Apache is www-data.
sudo groupadd www-data
sudo adduser www-data www-data
sudo chgrp -R www-data media
sudo chown -R www-data media
sudo chmod -R 770 media
By doing so, a new user group called "www-data" is created, the user "www-data" is added to it, the user group of the media is changed to "www-data," and finally the owner privileges are changed to "770," granting read, write, and execute rights to the owner (root) and owner group (www-data), but denying access to anyone else. Now that www-data is a member of the www-data group, it has the ability to read and write.