Permission Denied error with Django while uploading a file - django

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.

Related

Django error: OperationalError at /admin/auth/user/1/change/ [duplicate]

I was following the first app tutorial from the official Django docs and got this error when trying to save some changes made through the admin page. I did some research on it, but the possible solutions I was able to find, such as migrating the db, simply won't work. Just let me know if you want to see some specific part of my code.
Following is error:
OperationalError at /admin/polls/question/1/change/ no such table:
main.auth_user__old Request Method: POST Request
URL: http://127.0.0.1:8000/admin/polls/question/1/change/ Django
Version: 2.1.4 Exception Type: OperationalError Exception Value: no
such table: main.auth_user__old Exception
Location: /Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py
in execute, line 296 Python
Executable: /Users/gfioravante/Projects/test_app/ta_env/bin/python3
Python Version: 3.7.1 Python Path:
['/Users/gfioravante/Projects/test_app/test_app',
'/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
'/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
'/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
'/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages']
Server time: Wed, 5 Dec 2018 16:45:00 +0000
and the traceback:
Environment:
Request Method: POST Request URL:
http://127.0.0.1:8000/admin/polls/question/1/change/
Django Version: 2.1.4 Python Version: 3.7.1 Installed Applications:
['polls.apps.PollsConfig', 'django.contrib.admin',
'django.contrib.auth', 'django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.messages',
'django.contrib.staticfiles'] 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.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in _execute
85. return self.cursor.execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py"
in execute
296. return Database.Cursor.execute(self, query, params)
The above exception (no such table: main.auth_user__old) was the
direct cause of the following exception:
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/exception.py"
in inner
34. response = get_response(request)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/base.py"
in _get_response
126. response = self.process_exception_by_middleware(e, request)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/base.py"
in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in wrapper
604. return self.admin_site.admin_view(view)(*args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/utils/decorators.py"
in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/views/decorators/cache.py"
in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/sites.py" in inner
223. return view(request, *args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in change_view
1640. return self.changeform_view(request, object_id, form_url, extra_context)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/utils/decorators.py"
in _wrapper
45. return bound_method(*args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/utils/decorators.py"
in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in changeform_view
1525. return self._changeform_view(request, object_id, form_url, extra_context)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in _changeform_view
1571. self.log_change(request, new_object, change_message)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in log_change
826. change_message=message,
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/models.py"
in log_action
35. change_message=change_message,
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/manager.py"
in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/query.py"
in create
413. obj.save(force_insert=True, using=self.db)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
in save
718. force_update=force_update, update_fields=update_fields)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
in save_base
748. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
in _save_table
831. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
in _do_insert
869. using=using, raw=raw)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/manager.py"
in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/query.py"
in _insert
1136. return query.get_compiler(using=using).execute_sql(return_id)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/sql/compiler.py"
in execute_sql
1289. cursor.execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in execute
100. return super().execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in execute
68. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in _execute_with_wrappers
77. return executor(sql, params, many, context)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in _execute
85. return self.cursor.execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/utils.py"
in exit
89. raise dj_exc_value.with_traceback(traceback) from exc_value
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in _execute
85. return self.cursor.execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py"
in execute
296. return Database.Cursor.execute(self, query, params)
Exception Type: OperationalError at /admin/polls/question/1/change/
Exception Value: no such table: main.auth_user__old
Get rid of this issue easily maintaining the following steps:
keep django version 2.1.5 (the issue addressed in this version)
pip install django==2.1.5
Delete the SQLite db
Migrate again python manage.py makemigrations and then python manage.py migrate
Start the server python manage.py runserver
DONE!
I just came across this myself, it looks to be related to https://code.djangoproject.com/ticket/29182. For now, you can just downgrade your version of sqlite to a version prior to 2.6 (e.g. 2.5.1)
Just did this and it resolved the problem:
pip install Django --upgrade
Then:
python manage.py migrate
python manage.py makemigrations app
python manage.py migrate
Here is what I did to solve this problem:
Go to the virtual environment and install django#2.1.7
pip install django==2.1.7
Delete the db.sqlite3 file in your root folder.
Create the new db.sqlite3 in your root folder.
Re-run migrations:
python3 manage.py makemigrations
python3 manage.py migrate
Now it should be working all right.
The problem is caused by the modified behaviour of the ALTER TABLE RENAME statement in SQLite 3.26.0 (see compatiblity note). They also introduced the PRAGMA legacy_alter_table = ON statement in order to maintain the compatibility with previous versions. The upcoming Django release 2.1.5 utilizes the previously mentioned statement as a hotfix. It's expected on January 1, 2019.
go to this folder django/db/backends/sqlite3
backup schema.py file to another folder
open the original schema.py in a text editor
there you can see a code snippet like
def __enter__(self):
# Some SQLite schema alterations need foreign key constraints to be
# disabled. Enforce it here for the duration of the schema edition.
if not self.connection.disable_constraint_checking():
raise NotSupportedError(
'SQLite schema editor cannot be used while foreign key '
'constraint checks are enabled. Make sure to disable them '
'before entering a transaction.atomic() context because '
'SQLite3 does not support disabling them in the middle of '
'a multi-statement transaction.'
)
self.connection.cursor().execute('PRAGMA legacy_alter_table = ON')
return super().__enter__()
comment them and paste the following code snippet
def __enter__(self):
# Some SQLite schema alterations need foreign key constraints to be
# disabled. Enforce it here for the duration of the transaction.
self.connection.disable_constraint_checking()
self.connection.cursor().execute('PRAGMA legacy_alter_table = ON')
return super().__enter__()
This worked for me. (the backup for the schema.py is in case the work go wrong ; D
)
for more info
https://github.com/django/django/pull/10733/commits/c8ffdbe514b55ff5c9a2b8cb8bbdf2d3978c188f#diff-0c8f495bfee773ab7b5409533bd6d7ef
First, stop the server and delete db.sqlite3.
Then, you need to run:
python manage.py makemigrations
python manage.py migrate
After running this command you need to create super user. To Create
Super User, run:
python manage.py createsuperuser
Enter the super user details there.
Run your server again.
There you go.
I solved the problem by upgrading Django from 2.1.4 to 2.1.5 by running
pip install --upgrade django==2.1.5
but I had to rebuild the project anew, because the bug seems to be somehow related to the objects I inserted into the database by using the old version of Django.
UPDATE:
Instead of deleting the entire project, it was sufficient to delete only the database. And then to run
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
In my case, it was because of my django version (that was 2.1)
Install higher version (2.1.5+ or higher)
Delete db.sqlite3, and everything in migration folder except __init__.py
Run these commands:
pip install django==2.1.5 --upgrade
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
Even after upgrading to the latest Django 2.2.12 and running either migrate or the official database rebuild script, I got the same error with __old_:
django.db.utils.IntegrityError: The row in table 'djangocms_blog_post_translation' with primary key '2' has an invalid foreign key: djangocms_blog_post_translation.master_id contains a value '2' that does not have a corresponding value in djangocms_blog_post__old.id.
Here's my hack:
dump the database contents to sql: sqlite3 my_db.db .dump > my_db.sql
run a regex over the sql output, replacing __old" ("id") with " ("id") DEFERRABLE INITIALLY DEFERRED
delete the old database file
load the modified sql into a new database: sqlite3 my_db.db < my_db.sql
??? & profit
keep django version 2.1.5
This issue is adressed only in this version of Django
pip install django==2.1.5
Delete the SQLite db
Run migration
Start the server python manage.py runserver
This solves the above issue
Same thing is happened to me, very frustrating. I use anaconda for my environments, I found that I couldn't remove sqlite without immediately reinstalling the most up to date version of sqlite. Trying an older version of django also didn't seem to work. The only solution that has worked for me is by using a PostgreSQL database. It's certainly not ideal but I am planning on utilising the PostgreSQL database in the future so this wasn't a complete waste of time. If you find yourself in the same place as I was then this video may be helpful if you want to know how to connect the PostgreSQL database with your django project.
You'll need to install the postgreSQL database before actually making the changes in settings.py, the installation is more of less clicking Next on all the options. However, remember the username and password you use during installation.
Open => /YourAppFolder/migrations/ You would to see the migrating files just like '0001_initial.py' delete all of these files. And run the follwing command
1- python manage.py makemigrations
2- python manage.py migrate
Hope, it must solve your problem
For the above problem and solution is:
1) Go to the terminal and type in pip install django==2.1.7 or the latest version of django
2) After the installation,In the terminal type in python manage.py makemigrations,and then python manage.py migrate
3) In the terminal,Start the server with code python manage.py runserver
4) Login to the admin server with the password and the add the product,It will successfully add the product.
For others who don't want to downgrade any software, you can head into your settings.py file and in the DATABASES dict, you can replace .sqlit3 with .postgresql, and right underneath it change the db.sqlit3 to db.sql. This switches your default db to using postgreSQL.
In doing so, you'll need to pip install psycopg2.
Delete your db.sqlite3 file (if you have one/don't care about losing what's in it) and everything else that isn't the __init__.py file in your app's migration folder. Once you've done all of that, you can run python manage.py makemigrations and python manage.py migrate and then it should work :)
Hope I was able to help someone!
First, update django version:
pip install django --upgrade
then
./manage.py makemigration
./manage.py migrate
./manage.py runserver
There are just 4 things I did on command line and it fixed mine.
ctrl + c (stop server)
py manage.py makemigrations
py manage.py migrate
py manage.py runserver (start server)
I had the same issue except that I had 2 sqlite databases and custom database router. I managed to get it working by downgrading Django to 1.11.20 and no need to recreate the databases.
For those who cannot resolve this error with above answers, if you had made your app with its name “main”, this error may occur cause of same app name issue. So try to change your app name “main” to another.
you need to upgrade Django, this issue has been fixed in this PR https://github.com/django/django/pull/10733
I solved the problem by changing some of my models. I had one named project and one named projects. The database tables got confused and threw me this error.
I have solved this issue using below :
1) Delete the db.sqlit3
2) app's directory delete everything in
pycache
3) manage.py makemigrations, manage.py migrate, manage.py createsuperuser and then manage.py runserver.
I had the same issue and fixed it by doing the below:
1) Get the latest django version
2) get the latest SQL Lite version
3) delete db.sqlite3 file from your project
4) Make a small change to the models.py (e.g. change the size of a field)
5) generate a new db.sqllite3 file by running the makemigrations & migrate commands
6) import the newly created db.sqllite3 file into SQL Lite
I installed/downgraded django to 2.2 version ,this removed django 3.x
pip install django==2.2
and then I deleted db.sqlite file and then
I tried
python manage.py makemigrations,
python manage.py migrate
python manage.py creatingsuperuser.
Upgrade Django
pip install Django --upgrade
Delete the db.sqlite3 file the root folder of your project.
Create the new db.sqlite3 in your root folder by re-running migrations.
python3 manage.py makemigrations
Migrate
python3 manage.py migrate
It may work with just this or you may need to create a new superuser if it was deleted.
Check for your superuser using
python manage.py shell
from django.contrib.auth.models import User
User.objects.filter(is_superuser=True)
If <QuerySet []> appears there is no user.
Else check if your user exists.
If your user does not exist create one using
python manage.py createsuperuser
Steps:
Uninstall current Django from your ENV. Just delete the folder "anaconda3/envs/yourenv/lib/python3.7/site-packages/Django all versions..
Note: Only for Anaconda users, other users should figure out how to uninstall a package from your ENV.
Go to https://github.com/django/django.
Download the repo as zip file.
Extract zip.
Switch to your ENV.
Enter the extracted folder.
Run "python setup.py install" And install Django.
Delete your previous db.sqlite3 file. Now apply the migrations again to create a new db.sqlite3 file.
Note: I don't know how to fix previous dbfile and prevent data loss. So please tell me if you know.
Run Server.
Congrats! It works fine now.
Update to latest django in January from the official Django release.
Please check if you haven't deleted the migration folder from your app
if deleted try to restore the folder and remove migration files or
if deleted permanently create app and copy paste your work and
then
1. Delete db.sqlite3
2. python manage.py makemigrations
3. python manage.py migrate
4. python manage.py createsuperuser
HTH :)
Delete db.sqlite3
makemigrations & migrate
Create new super user
This works for me
Note: Do not follow this trick if you have some personal data in Sqlite3 DB as you're going to delete Sqlite3 DB
I know many answers are given to this question but only this trick help me to solve this issue as I'm beginner at python and learning Django.
Stopped the django webserver running, Ctrl-C
Delete the db.sqlite3
Uninstalled Django old verison
Install latest version of Django with “pip install django”
Delete all migrations from all apps of your project
Now run these commands in terminal
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser ( provide super-user credentials )
python manage.py runserver
Now finally login to admin panel with updated super-user's credentials and try to add record.
Same suggestions at this link by someone
django-2.2.7
This worked for me -
1) Delete db.sqlite3.
2) Within each app, within the migrations folder, delete everything other than __init__.py .
3) Within each app,delete __pycache__ folder.
I am not sure if you had to do it for all apps or just the concerned app, but this worked for me.

When I try to add new category in django admin, OperationalError at /admin/mediaportalapp/category/add/ [duplicate]

I was following the first app tutorial from the official Django docs and got this error when trying to save some changes made through the admin page. I did some research on it, but the possible solutions I was able to find, such as migrating the db, simply won't work. Just let me know if you want to see some specific part of my code.
Following is error:
OperationalError at /admin/polls/question/1/change/ no such table:
main.auth_user__old Request Method: POST Request
URL: http://127.0.0.1:8000/admin/polls/question/1/change/ Django
Version: 2.1.4 Exception Type: OperationalError Exception Value: no
such table: main.auth_user__old Exception
Location: /Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py
in execute, line 296 Python
Executable: /Users/gfioravante/Projects/test_app/ta_env/bin/python3
Python Version: 3.7.1 Python Path:
['/Users/gfioravante/Projects/test_app/test_app',
'/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
'/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
'/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
'/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages']
Server time: Wed, 5 Dec 2018 16:45:00 +0000
and the traceback:
Environment:
Request Method: POST Request URL:
http://127.0.0.1:8000/admin/polls/question/1/change/
Django Version: 2.1.4 Python Version: 3.7.1 Installed Applications:
['polls.apps.PollsConfig', 'django.contrib.admin',
'django.contrib.auth', 'django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.messages',
'django.contrib.staticfiles'] 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.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in _execute
85. return self.cursor.execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py"
in execute
296. return Database.Cursor.execute(self, query, params)
The above exception (no such table: main.auth_user__old) was the
direct cause of the following exception:
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/exception.py"
in inner
34. response = get_response(request)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/base.py"
in _get_response
126. response = self.process_exception_by_middleware(e, request)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/base.py"
in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in wrapper
604. return self.admin_site.admin_view(view)(*args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/utils/decorators.py"
in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/views/decorators/cache.py"
in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/sites.py" in inner
223. return view(request, *args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in change_view
1640. return self.changeform_view(request, object_id, form_url, extra_context)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/utils/decorators.py"
in _wrapper
45. return bound_method(*args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/utils/decorators.py"
in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in changeform_view
1525. return self._changeform_view(request, object_id, form_url, extra_context)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in _changeform_view
1571. self.log_change(request, new_object, change_message)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in log_change
826. change_message=message,
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/models.py"
in log_action
35. change_message=change_message,
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/manager.py"
in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/query.py"
in create
413. obj.save(force_insert=True, using=self.db)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
in save
718. force_update=force_update, update_fields=update_fields)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
in save_base
748. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
in _save_table
831. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
in _do_insert
869. using=using, raw=raw)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/manager.py"
in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/query.py"
in _insert
1136. return query.get_compiler(using=using).execute_sql(return_id)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/sql/compiler.py"
in execute_sql
1289. cursor.execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in execute
100. return super().execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in execute
68. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in _execute_with_wrappers
77. return executor(sql, params, many, context)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in _execute
85. return self.cursor.execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/utils.py"
in exit
89. raise dj_exc_value.with_traceback(traceback) from exc_value
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in _execute
85. return self.cursor.execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py"
in execute
296. return Database.Cursor.execute(self, query, params)
Exception Type: OperationalError at /admin/polls/question/1/change/
Exception Value: no such table: main.auth_user__old
Get rid of this issue easily maintaining the following steps:
keep django version 2.1.5 (the issue addressed in this version)
pip install django==2.1.5
Delete the SQLite db
Migrate again python manage.py makemigrations and then python manage.py migrate
Start the server python manage.py runserver
DONE!
I just came across this myself, it looks to be related to https://code.djangoproject.com/ticket/29182. For now, you can just downgrade your version of sqlite to a version prior to 2.6 (e.g. 2.5.1)
Just did this and it resolved the problem:
pip install Django --upgrade
Then:
python manage.py migrate
python manage.py makemigrations app
python manage.py migrate
Here is what I did to solve this problem:
Go to the virtual environment and install django#2.1.7
pip install django==2.1.7
Delete the db.sqlite3 file in your root folder.
Create the new db.sqlite3 in your root folder.
Re-run migrations:
python3 manage.py makemigrations
python3 manage.py migrate
Now it should be working all right.
The problem is caused by the modified behaviour of the ALTER TABLE RENAME statement in SQLite 3.26.0 (see compatiblity note). They also introduced the PRAGMA legacy_alter_table = ON statement in order to maintain the compatibility with previous versions. The upcoming Django release 2.1.5 utilizes the previously mentioned statement as a hotfix. It's expected on January 1, 2019.
go to this folder django/db/backends/sqlite3
backup schema.py file to another folder
open the original schema.py in a text editor
there you can see a code snippet like
def __enter__(self):
# Some SQLite schema alterations need foreign key constraints to be
# disabled. Enforce it here for the duration of the schema edition.
if not self.connection.disable_constraint_checking():
raise NotSupportedError(
'SQLite schema editor cannot be used while foreign key '
'constraint checks are enabled. Make sure to disable them '
'before entering a transaction.atomic() context because '
'SQLite3 does not support disabling them in the middle of '
'a multi-statement transaction.'
)
self.connection.cursor().execute('PRAGMA legacy_alter_table = ON')
return super().__enter__()
comment them and paste the following code snippet
def __enter__(self):
# Some SQLite schema alterations need foreign key constraints to be
# disabled. Enforce it here for the duration of the transaction.
self.connection.disable_constraint_checking()
self.connection.cursor().execute('PRAGMA legacy_alter_table = ON')
return super().__enter__()
This worked for me. (the backup for the schema.py is in case the work go wrong ; D
)
for more info
https://github.com/django/django/pull/10733/commits/c8ffdbe514b55ff5c9a2b8cb8bbdf2d3978c188f#diff-0c8f495bfee773ab7b5409533bd6d7ef
First, stop the server and delete db.sqlite3.
Then, you need to run:
python manage.py makemigrations
python manage.py migrate
After running this command you need to create super user. To Create
Super User, run:
python manage.py createsuperuser
Enter the super user details there.
Run your server again.
There you go.
I solved the problem by upgrading Django from 2.1.4 to 2.1.5 by running
pip install --upgrade django==2.1.5
but I had to rebuild the project anew, because the bug seems to be somehow related to the objects I inserted into the database by using the old version of Django.
UPDATE:
Instead of deleting the entire project, it was sufficient to delete only the database. And then to run
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
In my case, it was because of my django version (that was 2.1)
Install higher version (2.1.5+ or higher)
Delete db.sqlite3, and everything in migration folder except __init__.py
Run these commands:
pip install django==2.1.5 --upgrade
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
Even after upgrading to the latest Django 2.2.12 and running either migrate or the official database rebuild script, I got the same error with __old_:
django.db.utils.IntegrityError: The row in table 'djangocms_blog_post_translation' with primary key '2' has an invalid foreign key: djangocms_blog_post_translation.master_id contains a value '2' that does not have a corresponding value in djangocms_blog_post__old.id.
Here's my hack:
dump the database contents to sql: sqlite3 my_db.db .dump > my_db.sql
run a regex over the sql output, replacing __old" ("id") with " ("id") DEFERRABLE INITIALLY DEFERRED
delete the old database file
load the modified sql into a new database: sqlite3 my_db.db < my_db.sql
??? & profit
keep django version 2.1.5
This issue is adressed only in this version of Django
pip install django==2.1.5
Delete the SQLite db
Run migration
Start the server python manage.py runserver
This solves the above issue
Same thing is happened to me, very frustrating. I use anaconda for my environments, I found that I couldn't remove sqlite without immediately reinstalling the most up to date version of sqlite. Trying an older version of django also didn't seem to work. The only solution that has worked for me is by using a PostgreSQL database. It's certainly not ideal but I am planning on utilising the PostgreSQL database in the future so this wasn't a complete waste of time. If you find yourself in the same place as I was then this video may be helpful if you want to know how to connect the PostgreSQL database with your django project.
You'll need to install the postgreSQL database before actually making the changes in settings.py, the installation is more of less clicking Next on all the options. However, remember the username and password you use during installation.
Open => /YourAppFolder/migrations/ You would to see the migrating files just like '0001_initial.py' delete all of these files. And run the follwing command
1- python manage.py makemigrations
2- python manage.py migrate
Hope, it must solve your problem
For the above problem and solution is:
1) Go to the terminal and type in pip install django==2.1.7 or the latest version of django
2) After the installation,In the terminal type in python manage.py makemigrations,and then python manage.py migrate
3) In the terminal,Start the server with code python manage.py runserver
4) Login to the admin server with the password and the add the product,It will successfully add the product.
For others who don't want to downgrade any software, you can head into your settings.py file and in the DATABASES dict, you can replace .sqlit3 with .postgresql, and right underneath it change the db.sqlit3 to db.sql. This switches your default db to using postgreSQL.
In doing so, you'll need to pip install psycopg2.
Delete your db.sqlite3 file (if you have one/don't care about losing what's in it) and everything else that isn't the __init__.py file in your app's migration folder. Once you've done all of that, you can run python manage.py makemigrations and python manage.py migrate and then it should work :)
Hope I was able to help someone!
First, update django version:
pip install django --upgrade
then
./manage.py makemigration
./manage.py migrate
./manage.py runserver
There are just 4 things I did on command line and it fixed mine.
ctrl + c (stop server)
py manage.py makemigrations
py manage.py migrate
py manage.py runserver (start server)
I had the same issue except that I had 2 sqlite databases and custom database router. I managed to get it working by downgrading Django to 1.11.20 and no need to recreate the databases.
For those who cannot resolve this error with above answers, if you had made your app with its name “main”, this error may occur cause of same app name issue. So try to change your app name “main” to another.
you need to upgrade Django, this issue has been fixed in this PR https://github.com/django/django/pull/10733
I solved the problem by changing some of my models. I had one named project and one named projects. The database tables got confused and threw me this error.
I have solved this issue using below :
1) Delete the db.sqlit3
2) app's directory delete everything in
pycache
3) manage.py makemigrations, manage.py migrate, manage.py createsuperuser and then manage.py runserver.
I had the same issue and fixed it by doing the below:
1) Get the latest django version
2) get the latest SQL Lite version
3) delete db.sqlite3 file from your project
4) Make a small change to the models.py (e.g. change the size of a field)
5) generate a new db.sqllite3 file by running the makemigrations & migrate commands
6) import the newly created db.sqllite3 file into SQL Lite
I installed/downgraded django to 2.2 version ,this removed django 3.x
pip install django==2.2
and then I deleted db.sqlite file and then
I tried
python manage.py makemigrations,
python manage.py migrate
python manage.py creatingsuperuser.
Upgrade Django
pip install Django --upgrade
Delete the db.sqlite3 file the root folder of your project.
Create the new db.sqlite3 in your root folder by re-running migrations.
python3 manage.py makemigrations
Migrate
python3 manage.py migrate
It may work with just this or you may need to create a new superuser if it was deleted.
Check for your superuser using
python manage.py shell
from django.contrib.auth.models import User
User.objects.filter(is_superuser=True)
If <QuerySet []> appears there is no user.
Else check if your user exists.
If your user does not exist create one using
python manage.py createsuperuser
Steps:
Uninstall current Django from your ENV. Just delete the folder "anaconda3/envs/yourenv/lib/python3.7/site-packages/Django all versions..
Note: Only for Anaconda users, other users should figure out how to uninstall a package from your ENV.
Go to https://github.com/django/django.
Download the repo as zip file.
Extract zip.
Switch to your ENV.
Enter the extracted folder.
Run "python setup.py install" And install Django.
Delete your previous db.sqlite3 file. Now apply the migrations again to create a new db.sqlite3 file.
Note: I don't know how to fix previous dbfile and prevent data loss. So please tell me if you know.
Run Server.
Congrats! It works fine now.
Update to latest django in January from the official Django release.
Please check if you haven't deleted the migration folder from your app
if deleted try to restore the folder and remove migration files or
if deleted permanently create app and copy paste your work and
then
1. Delete db.sqlite3
2. python manage.py makemigrations
3. python manage.py migrate
4. python manage.py createsuperuser
HTH :)
Delete db.sqlite3
makemigrations & migrate
Create new super user
This works for me
Note: Do not follow this trick if you have some personal data in Sqlite3 DB as you're going to delete Sqlite3 DB
I know many answers are given to this question but only this trick help me to solve this issue as I'm beginner at python and learning Django.
Stopped the django webserver running, Ctrl-C
Delete the db.sqlite3
Uninstalled Django old verison
Install latest version of Django with “pip install django”
Delete all migrations from all apps of your project
Now run these commands in terminal
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser ( provide super-user credentials )
python manage.py runserver
Now finally login to admin panel with updated super-user's credentials and try to add record.
Same suggestions at this link by someone
django-2.2.7
This worked for me -
1) Delete db.sqlite3.
2) Within each app, within the migrations folder, delete everything other than __init__.py .
3) Within each app,delete __pycache__ folder.
I am not sure if you had to do it for all apps or just the concerned app, but this worked for me.

I have a GeocoderQueryError and suspect it's an issue with my API management

GeocoderQueryError at /search/
Your request was denied.
I'm seeing this issue across all versions of my application. That is locally, on staging, and on production. This leads me to believe it's something I've done in the API console since I haven't touched production and only touched the API call on staging. I have been in the API console but have only added IP addresses to "Accept requests from these server IP addresses" input in the credentials tab.
Here is the staging link: test.translgx.com
You'll only see a 500 page after searching for a ZIP code. I've included the full error report from my local installation at the bottom of the post, I hope this is helpful. If not, let me know and I'll do what I can to get the info needed to solve this.
Full disclosure, I'm a front-end guy and don't have the debugging/diagnostic skills needed to figure this out. I also don't have any back-end dev support available to me until next week. Google's support docs tell me to come here with questions so I'm hoping someone here shows mercy and points me in the right direction.
I should also note that the API key I see in production doesn't match any key in my console.
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/search/?address=94133&distance=zip&truck=
Django Version: 1.9.4
Python Version: 2.7.11
Installed Applications:
('django_pdb',
u'django.contrib.auth',
u'django.contrib.contenttypes',
u'django.contrib.sessions',
u'django.contrib.sites',
u'django.contrib.messages',
u'django.contrib.staticfiles',
u'django.contrib.admin',
u'django.contrib.gis',
u'crispy_forms',
u'post_office',
u'widget_tweaks',
u'captcha',
u'geoposition',
u'cities_light',
u'templatetag_handlebars',
u'trucking_directory.common.apps.CommonConfig',
'debug_toolbar',
'django_extensions')
Installed Middleware:
(u'django.contrib.sessions.middleware.SessionMiddleware',
u'django.middleware.common.CommonMiddleware',
u'django.middleware.csrf.CsrfViewMiddleware',
u'django.contrib.auth.middleware.AuthenticationMiddleware',
u'django.contrib.messages.middleware.MessageMiddleware',
u'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django_pdb.middleware.PdbMiddleware')
Traceback:
File "/Users/me/Envs/tlx-d/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 149.
response = self.process_exception_by_middleware(e, request)
File "/Users/me/Envs/tlx-d/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 147.
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/me/Envs/tlx-d/lib/python2.7/site-packages/django/utils/decorators.py" in inner 184.
return func(*args, **kwargs)
File "/Users/me/Envs/tlx-d/lib/python2.7/site-packages/django/views/generic/base.py" in view 68.
return self.dispatch(request, *args, **kwargs)
File "/Users/me/Envs/tlx-d/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch 88.
return handler(request, *args, **kwargs)
File "/Users/me/Sites/_app/trucking-directory/trucking_directory/common/views.py" in get 261.
self.form.is_valid()
File "/Users/me/Envs/tlx-d/lib/python2.7/site-packages/django/forms/forms.py" in is_valid 161.
return self.is_bound and not self.errors
File "/Users/me/Envs/tlx-d/lib/python2.7/site-packages/django/forms/forms.py" in errors 153.
self.full_clean()
File "/Users/me/Envs/tlx-d/lib/python2.7/site-packages/django/forms/forms.py" in full_clean 362.
self._clean_fields()
File "/Users/me/Envs/tlx-d/lib/python2.7/site-packages/django/forms/forms.py" in _clean_fields 383.
value = getattr(self, 'clean_%s' % name)()
File "/Users/me/Sites/_app/trucking-directory/trucking_directory/common/forms.py" in clean_address 218.
locations = _get_location(data, False)
File "/Users/me/Sites/_app/trucking-directory/trucking_directory/common/forms.py" in _get_location 38.
location = g.geocode(address, exactly_one=one)
File "/Users/me/Envs/tlx-d/lib/python2.7/site-packages/geopy/geocoders/googlev3.py" in geocode 217.
self._call_geocoder(url, timeout=timeout), exactly_one
File "/Users/me/Envs/tlx-d/lib/python2.7/site-packages/geopy/geocoders/googlev3.py" in _parse_json 338.
self._check_status(page.get('status'))
File "/Users/me/Envs/tlx-d/lib/python2.7/site-packages/geopy/geocoders/googlev3.py" in _check_status 369.
'Your request was denied.'
Exception Type: GeocoderQueryError at /search/
Exception Value: Your request was denied.
You probably need to add an API key. If you don't have one, try the GET A KEY in the top-left corner of the Geocoding API guide. The, I think this code should work (borrowed from here):
from geopy.geocoders import GoogleV3
point = '51.523910, -0.158578'
geocoder = GoogleV3(api_key=YOUR_API_KEY)
address = geolocator.reverse(point)

Django - Media upload [Errno 13] Permission denied

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/'

Django / mod_wsgi / postgresql_psycopg2: can't connect authentication fails (but settings work fine under django runserver or dbshell)

I'm deploying my django site on a Ubuntu 8.10 server that I've set up from scratch. I'm totally new to this so there may be plenty of stuff that I've missed, but happily have found my way through to the point of deploying a website.
My last hurdle:
I'm getting an authentication error with postgresql
[Sun Apr 19 18:44:05 2009] [error] [client 124.254.102.127]
mod_wsgi (pid=30304): Exception occurred processing WSGI script '/home/acacian/webapps/acacian/deploy/acacian.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/handlers/wsgi.py", line 241, in __call__
response = self.get_response(request)
File "/usr/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/handlers/base.py", line 73, in get_response
response = middleware_method(request)
File "/home/acacian/webapps/pinax-env/src/django-openid/django_openid/consumer.py", line 383, in process_request
if self.session_key in request.session:
File "/usr/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/contrib/sessions/backends/base.py", line 43, in __contains__
return key in self._session
File "/usr/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/contrib/sessions/backends/base.py", line 172, in _get_session
self._session_cache = self.load()
File "/usr/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/contrib/sessions/backends/db.py", line 16, in load
expire_date__gt=datetime.datetime.now()
File "/usr/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/db/models/manager.py", line 120, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/db/models/query.py", line 269, in get
num = len(clone)
File "/usr/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/db/models/query.py", line 68, in __len__
self._result_cache = list(self.iterator())
File "/usr/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/db/models/query.py", line 207, in iterator
for row in self.query.results_iter():
File "/usr/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/db/models/sql/query.py", line 262, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/db/models/sql/query.py", line 2288, in execute_sql
cursor = self.connection.cursor()
File "/usr/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/db/backends/__init__.py", line 81, in cursor
cursor = self._cursor()
File "/usr/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/db/backends/postgresql_psycopg2/base.py", line 98, in _cursor
self.connection = Database.connect(**conn_params)
OperationalError: FATAL: Ident authentication failed for user "acacian"
Note:
the same settings work fine under runserver and dbshell
mod_wsgi has been working with sqlite3 (i'm at the point of switching over)
acacian.wsgi (a little messy)
# basic_project.wsgi is configured to live in projects/basic_project/deploy.
import os
import sys
import site
sys.stdout = sys.stderr
from os.path import abspath, dirname, join
from site import addsitedir
# the project path & pinax src paths
sys.path.insert(0, abspath(join(dirname(__file__), "../../")))
sys.path.insert(0, abspath(join(dirname(__file__), "../../pinax-env/src/pinax")))
sys.path.insert(0, abspath(join(dirname(__file__), "../../pinax-env/src")))
sys.path = ['/home/acacian/webapps/acacian/apps', '/home/acacian/webapps/pinax-env/src/pinax/pinax/apps', '/home/acacian/webapps/acacian', '/home/acacian/webapps/pinax-env/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg', '/home/acacian/webapps/pinax-env/lib/python2.5/site-packages/pip-0.3.1-py2.5.egg', '/home/acacian/webapps/pinax-env/src/pinax', '/home/acacian/webapps/pinax-env/src/django-openid', '/home/acacian/webapps/pinax-env/src/atom-format', '/home/acacian/webapps/pinax-env/src/django-app-plugins', '/home/acacian/webapps/pinax-env/src/diff-match-patch', '/usr/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg', '/usr/lib/python2.5/site-packages/pip-0.3.1-py2.5.egg', '/home/acacian/webapps/pinax-env/lib/python2.5', '/home/acacian/webapps/pinax-env/lib/python2.5/plat-linux2', '/home/acacian/webapps/pinax-env/lib/python2.5/lib-tk', '/home/acacian/webapps/pinax-env/lib/python2.5/lib-dynload', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/home/acacian/webapps/pinax-env/lib/python2.5/site-packages', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/PIL', '/var/lib/python-support/python2.5'] + sys.path
# A version of activate_this from the mod_wsgi documentation site.
ALLDIRS = ['/home/acacian/webapps/acacian/pinax-env/lib/python2.5/site-packages']
# Remember original sys.path.
prev_sys_path = list(sys.path)
# Add each new site-packages directory.
for directory in ALLDIRS:
site.addsitedir(directory)
# Reorder sys.path so new directories at the front.
new_sys_path = []
for item in list(sys.path):
if item not in prev_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_path
#print sys.path
from django.conf import settings
os.environ["DJANGO_SETTINGS_MODULE"] = "acacian.settings"
sys.path.insert(0, join(settings.PINAX_ROOT, "apps"))
sys.path.insert(0, join(settings.PROJECT_ROOT, "apps"))
from django.core.handlers.wsgi import WSGIHandler
application = WSGIHandler()
Thank you!
The error:
Ident authentication failed for user "acacian"
means just that.
When you are using runserver or dbshell the Django process is running with your userid as process owner.
When you run Django under mod_wsgi, in daemon mode, it is running as the user specified in the WSGIDaemonProcess directive. If you are running mod_wsgi in embedded (non-daemon) mode then the userid will match the Apache process User directive.
So, what you need to do is add your user acacian as a user to postgresql using createuser just like you did with your own user name.
It could be your postgres connection settings. I think postgres authenticates by default using the unix userid, but in this case you might want to use standard username/password authentication (since that's what you've hardcoded into the django settings). So you might try:
sudo vi /etc/postgresql/8.4/main/pg_hba.conf
(or emacs or nano etc). Then change the following line:
local all all ident
to:
local all all password
You might find this blogpost helpful http://www.depesz.com/index.php/2007/10/04/ident/ - it tries to explain the "Ident authentication failed" error, it's source, and what can you do about it.
My guess is that your issue is in the database connection settings (settings.py). I am assuming you have already created the database and syncdb'd etc?
This article is awesome for setting up Django/Postgres/etc on Ubuntu 8.10 (I have followed it to set up a couple of VMs already):
http://lethain.com/entry/2009/feb/13/the-django-and-ubuntu-intrepid-almanac/