So I want to asynchronously conduct file saves to django file storage. I've tried to achieve this by overwriting the default File System Storage class.
import hashlib
import os
import uuid
import django.core.files.storage as storage
from celery import shared_task
from django.core.files import File
class DefaultStorage(storage.FileSystemStorage):
def __init__(self):
super(DefaultStorage, self).__init__()
#shared_task
def _save(self, name, content):
# need to encrypt file before saving
return super(DefaultStorage, self)._save(name, content)
#shared_task
def _open(self, name, mode='rb'):
# need to decrypt before opening
return File(open(self.path(name), mode))
def get_available_name(self, name, max_length=None):
# we return a hash of the file given,
# in case we miss out on uniqueness, django calls
# the get_alternative_name method
dir_name, file_name = os.path.split(name)
file_root, file_ext = os.path.splitext(file_name)
file_root = hashlib.md5(file_root.encode()).hexdigest()
name = os.path.join(dir_name, file_root + file_ext)
return super(DefaultStorage, self).get_available_name(name, max_length)
def get_alternative_name(self, file_root, file_ext):
# we insert a random uuid hex string into the given
# file name before returning the same back
return '%s%s%s' % (file_root, uuid.uuid4().hex, file_ext)
def save(self, name, content, max_length=None):
# override existing system storage save method
# to ensure that we call the shared task and
# utilize the distributed task queue celery offers
has_chunks = hasattr(content, 'chunks')
name = content.name if not name else name
content = File(content, name) if not has_chunks else content
name = self.get_available_name(name, max_length=max_length)
saved = self._save.delay(self, name, content)
return saved
def open(self, name, mode='rb'):
# override existing system storage open method
# to ensure that we call the shared task and
# utilize the distributed task queue celery offers
return self._open.delay(name, mode)
The idea is to override the existing save method to fire off the shared_task named _save. However, I am facing the following error while trying to do the same.
Traceback (most recent call last):
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\generics.py", line 242, in post
return self.create(request, *args, **kwargs)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\mixins.py", line 19, in create
self.perform_create(serializer)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\mixins.py", line 24, in perform_create
serializer.save()
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\serializers.py", line 205, in save
self.instance = self.create(validated_data)
File "C:\Users\iyapp\PycharmProjects\cloud-server\api_backend\serializers\partial.py", line 32, in create
return super(PartialUploadSerializer, self).create(validated_data)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\serializers.py", line 939, in create
instance = ModelClass._default_manager.create(**validated_data)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\query.py", line 447, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\iyapp\PycharmProjects\cloud-server\api_backend\models\uploads.py", line 30, in save
super(Upload, self).save(*args, **kwargs)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\base.py", line 754, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\base.py", line 792, in save_base
force_update, using, update_fields,
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\base.py", line 895, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\base.py", line 935, in _do_insert
using=using, raw=raw,
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1396, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1341, in as_sql
for obj in self.query.objs
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1341, in <listcomp>
for obj in self.query.objs
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1340, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1291, in pre_save_val
return field.pre_save(obj, add=True)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\fields\files.py", line 307, in pre_save
file.save(file.name, file.file, save=False)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\fields\files.py", line 87, in save
self.name = self.storage.save(name, content, max_length=self.field.max_length)
File "C:\Users\iyapp\PycharmProjects\cloud-server\api_backend\models\storage\default_storage.py", line 48, in save
saved = self._save.delay(self, name, content)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\celery\app\task.py", line 421, in delay
return self.apply_async(args, kwargs)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\celery\app\task.py", line 565, in apply_async
**options
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\celery\app\base.py", line 749, in send_task
amqp.send_task_message(P, name, message, **options)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\celery\app\amqp.py", line 532, in send_task_message
**properties
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\messaging.py", line 166, in publish
compression, headers)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\messaging.py", line 249, in _prepare
body) = dumps(body, serializer=serializer)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\serialization.py", line 220, in dumps
payload = encoder(data)
File "C:\Users\iyapp\AppData\Local\Programs\Python\Python36-32\lib\contextlib.py", line 99, in __exit__
self.gen.throw(type, value, traceback)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\serialization.py", line 53, in _reraise_errors
reraise(wrapper, wrapper(exc), sys.exc_info()[2])
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\exceptions.py", line 21, in reraise
raise value.with_traceback(tb)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\serialization.py", line 49, in _reraise_errors
yield
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\serialization.py", line 220, in dumps
payload = encoder(data)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\utils\json.py", line 66, in dumps
**dict(default_kwargs, **kwargs))
File "C:\Users\iyapp\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Users\iyapp\AppData\Local\Programs\Python\Python36-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\iyapp\AppData\Local\Programs\Python\Python36-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\utils\json.py", line 55, in default
return super().default(o)
File "C:\Users\iyapp\AppData\Local\Programs\Python\Python36-32\lib\json\encoder.py", line 180, in default
o.__class__.__name__)
kombu.exceptions.EncodeError: Object of type 'DefaultStorage' is not JSON serializable
I believe I have found the source of the issue. It is because we cannot pass "file" objects as parameters to shared_task functions. If this is the case, then how can I send my file to the _save function?
Before sending, the file isn't saved yet. We need to save the file only after receiving.
Related
I have the following in adapter.py:
from allauth.account.adapter import DefaultAccountAdapter
class CustomAllauthAdapter(DefaultAccountAdapter):
pass # keeping it trivial for debugging
At the very bottom of settings.py:
import django
django.setup() # complains about apps not being loaded yet without this...
from .adapter import CustomAllauthAdapter
ACCOUNT_ADAPTER = CustomAllauthAdapter # this is the line that results in the error!
As soon as I submit the registration form for a new user, I get this error in the browser:
AssertionError at /api/v1/users/auth/register/
No exception message supplied
Here is the Traceback:
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\dj_rest_auth\registration\views.py", line 47, in dispatch
return super().dispatch(*args, **kwargs)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\generics.py", line 190, in post
return self.create(request, *args, **kwargs)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\dj_rest_auth\registration\views.py", line 66, in create
serializer.is_valid(raise_exception=True)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\serializers.py", line 220, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\serializers.py", line 419, in run_validation
value = self.to_internal_value(data)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\rest_framework\serializers.py", line 478, in to_internal_value
validated_value = validate_method(validated_value)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\dj_rest_auth\registration\serializers.py", line 209, in validate_email
email = get_adapter().clean_email(email)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\allauth\account\adapter.py", line 535, in get_adapter
return import_attribute(app_settings.ADAPTER)(request)
File "C:\Dropbox\Parnasa\Web\drmeir\env\lib\site-packages\allauth\utils.py", line 153, in import_attribute
assert isinstance(path, str)
If I do not set the ACCOUNT_ADAPTER, everything works well including registration and authentication. I need to use custom account adapter to customize email verification.
Why am I getting the error and what should I do to fix it?
No need to import anything and no need for django.setup(). The configuration variable is a string!
ACCOUNT_ADAPTER = 'users.adapter.CustomAllauthAdapter'
I want to store the image files in the S3 and the video files in the Vimeo in my django project. I am S3Boto3Storage of Django-storage as the storage backend. As Vimeo takes care of compression and content delivery for video files and it's cheap compared to S3, I want to use that for video files.
I thought of uploading the file to the Vimeo using the upload_to attribute in the FileField of django model, but I can't able to get the absolute path of the video file in the method.
here is my implementation of the upload_to method,
import vimeo
def vimeo_client():
client = vimeo.VimeoClient(
token=settings.VIMEO_ACCESS_TOKEN,
key=settings.VIMEO_CLIENT_ID,
secret=settings.VIMEO_CLIENT_SECRET
)
return client
def get_media_path(instance, filename):
new_filename = '{}.{}'.format(uuid.uuid4(), filename.split('.')[-1])
if instance.type == 'image':
file_path = 'posts/media/images/{filename}'.format(
filename=new_filename)
else:
client = vimeo_client()
file_path = client.upload(
filename,
data={
'name': instance.title,
'description': instance.description
}
)
logger.info("File uploaded to: [{}]".format(file_path))
return file_path
But it's giving me this error
OSError: [Errno 2] No such file or directory: 'videoplayback.mp4'
Or I could customise the S3Boto3Storage for my purpose. I would like to know what would be the better solution.
Edit
Here is the full stack trace
Traceback (most recent call last):
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 157, in __call__
response = self.get_response(request)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/core/handlers/base.py", line 124, in get_response
response = self._middleware_chain(request)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/core/handlers/exception.py", line 43, in inner
response = response_for_exception(request, exc)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/core/handlers/exception.py", line 93, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/core/handlers/exception.py", line 139, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/Users/rohanroy/development/django/zappa/appcore/src/appcore/wsgi.py", line 24, in null_technical_500_response
six.reraise(exc_type, exc_value, tb)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/contrib/admin/options.py", line 551, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/utils/decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 224, in inner
return view(request, *args, **kwargs)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1508, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/utils/decorators.py", line 67, in _wrapper
return bound_func(*args, **kwargs)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/utils/decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/utils/decorators.py", line 63, in bound_func
return func.__get__(self, type(self))(*args2, **kwargs2)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1408, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1448, in _changeform_view
self.save_model(request, new_object, form, not add)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/contrib/admin/options.py", line 979, in save_model
obj.save()
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/db/models/base.py", line 808, in save
force_update=force_update, update_fields=update_fields)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/db/models/base.py", line 838, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/db/models/base.py", line 924, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/db/models/base.py", line 963, in _do_insert
using=using, raw=raw)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/db/models/query.py", line 1076, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1112, in execute_sql
for sql, params in self.as_sql():
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1065, in as_sql
for obj in self.query.objs
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1014, in pre_save_val
return field.pre_save(obj, add=True)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/db/models/fields/files.py", line 296, in pre_save
file.save(file.name, file.file, save=False)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/db/models/fields/files.py", line 93, in save
name = self.field.generate_filename(self.instance, name)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/django/db/models/fields/files.py", line 327, in generate_filename
filename = self.upload_to(instance, filename)
File "/Users/rohanroy/development/django/zappa/appcore/src/utils/common.py", line 50, in get_media_path
'description': instance.description
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/vimeo/upload.py", line 49, in upload
filesize = self.__get_file_size(filename)
File "/Users/rohanroy/development/django/zappa/arete/lib/python2.7/site-packages/vimeo/upload.py", line 163, in __get_file_size
return os.path.getsize(filename)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py", line 57, in getsize
return os.stat(filename).st_size
OSError: [Errno 2] No such file or directory: 'videoplayback.mp4'
Vimeo API's supports 3 types of video upload strategies which are discussed here. The tus approach assumes that the video file is in the local system. To upload video from the browser one need to use the form-based uploads approach which is not useful for an API only server. There is two option to tackle this,
Upload the video from the client-side to the API server using your own API endpoint and then use vimeo.py to upload it to the Vimeo and delete the actual video file from the server.
Use vimeo.js to upload the video file from the client side and then store the returned video_uri in the backend.
I'm currently using #receiver to add a token to new users like so -
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
What I also want to be able to do is create a default WidgetList based on this model:
class WidgetList(MPTTModel):
name = models.CharField(max_length=100)
description = models.CharField(max_length=1024)
owner = models.ForeignKey('MyAppUser')
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
def __str__(self):
return self.name
class MPTTMEta:
order_insertion_by = ['name']
I tried making another reciever -
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_root_list(sender, instance=None, created=False, **kwargs):
if created:
WidgetList.objects.create(user=instance)
EDIT - on the initial python manage.py migrate I get the following traceback:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/opt/myproject_app/lib/python2.7/site-packages/django/core/management/__init__.py", line 351, in execute_from_command_line
utility.execute()
File "/opt/myproject_app/lib/python2.7/site-packages/django/core/management/__init__.py", line 343, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/opt/myproject_app/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv
self.execute(*args, **cmd_options)
File "/opt/myproject_app/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute
output = self.handle(*args, **options)
File "/opt/myproject_app/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 226, in handle
emit_post_migrate_signal(created_models, self.verbosity, self.interactive, connection.alias)
File "/opt/myproject_app/lib/python2.7/site-packages/django/core/management/sql.py", line 280, in emit_post_migrate_signal
using=db)
File "/opt/myproject_app/lib/python2.7/site-packages/django/dispatch/dispatcher.py", line 201, in send
response = receiver(signal=self, sender=sender, **named)
File "/opt/myproject_app/lib/python2.7/site-packages/guardian/management/__init__.py", line 39, in create_anonymous_user
user.save()
File "/opt/myproject_app/lib/python2.7/site-packages/django/db/models/base.py", line 734, in save
force_update=force_update, update_fields=update_fields)
File "/opt/myproject_app/lib/python2.7/site-packages/django/db/models/base.py", line 771, in save_base
update_fields=update_fields, raw=raw, using=using)
File "/opt/myproject_app/lib/python2.7/site-packages/django/dispatch/dispatcher.py", line 201, in send
response = receiver(signal=self, sender=sender, **named)
File "/opt/myproject/core/models.py", line 18, in create_root_list
WidgetList.objects.create(user=instance)
File "/opt/myproject_app/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/opt/myproject_app/lib/python2.7/site-packages/django/db/models/query.py", line 346, in create
obj = self.model(**kwargs)
File "/opt/myproject_app/lib/python2.7/site-packages/mptt/models.py", line 393, in __init__
super(MPTTModel, self).__init__(*args, **kwargs)
File "/opt/myproject_app/lib/python2.7/site-packages/django/db/models/base.py", line 480, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'user' is an invalid keyword argument for this function
this is the second traceback if I try to rerun migrate:
Traceback (most recent call last):
File "/opt/myproject_app/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/opt/myproject_app/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/opt/myproject_app/lib/python2.7/site-packages/rest_framework/viewsets.py", line 87, in view
return self.dispatch(request, *args, **kwargs)
File "/opt/myproject_app/lib/python2.7/site-packages/rest_framework_encrypted_lookup/views.py", line 41, in dispatch
return super(EncryptedLookupGenericViewSet, self).dispatch(request, *args, **kwargs)
File "/opt/myproject_app/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/opt/myproject_app/lib/python2.7/site-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, *args, **kwargs)
File "/opt/myproject_app/lib/python2.7/site-packages/rest_framework/mixins.py", line 21, in create
self.perform_create(serializer)
File "/opt/myproject_app/lib/python2.7/site-packages/rest_framework/mixins.py", line 26, in perform_create
serializer.save()
File "/opt/myproject_app/lib/python2.7/site-packages/rest_framework/serializers.py", line 191, in save
self.instance = self.create(validated_data)
File "/opt/myproject/api/serializers.py", line 106, in create
validated_data['parent'] = WidgetList.objects.get(pk=user_parent_list)
File "/opt/myproject_app/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/opt/myproject_app/lib/python2.7/site-packages/django/db/models/query.py", line 334, in get
self.model._meta.object_name
DoesNotExist: WidgetList matching query does not exist.
Comparing your traceback and your code, you can find that error happens here:
WidgetList.objects.create(user=instance)
Your model WidgetList doesn't even have user field, so it's pretty obvious that you cannot do that. Maybe you were copying & paste the code that caused an error.
There is no user in your model. Which I see you mean owner.
You will get foreign key ref errors as there is not data. Load some parent data using fixture. That would solve this issue.
I have a django app which is running on 1.6 with python 3. Recently I have added django-storages to my app.
When I am trying to save a model(record) which worked well previously, its showing up the below error
Traceback (most recent call last):
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/core/handlers/base.py", line 112, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/contrib/admin/options.py", line 432, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/utils/decorators.py", line 99, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/views/decorators/cache.py", line 52, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/contrib/admin/sites.py", line 198, in inner
return view(request, *args, **kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/utils/decorators.py", line 29, in _wrapper
return bound_func(*args, **kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/utils/decorators.py", line 99, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/utils/decorators.py", line 25, in bound_func
return func(self, *args2, **kwargs2)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/transaction.py", line 371, in inner
return func(*args, **kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/contrib/admin/options.py", line 1131, in add_view
self.save_model(request, new_object, form, False)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/contrib/admin/options.py", line 860, in save_model
obj.save()
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/base.py", line 545, in save
force_update=force_update, update_fields=update_fields)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/base.py", line 573, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/base.py", line 654, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/base.py", line 687, in _do_insert
using=using, raw=raw)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/manager.py", line 232, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/query.py", line 1514, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 902, in execute_sql
for sql, params in self.as_sql():
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 860, in as_sql
for obj in self.query.objs
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 860, in <listcomp>
for obj in self.query.objs
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 858, in <listcomp>
for f in fields
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/fields/files.py", line 252, in pre_save
file.save(file.name, file, save=False)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/fields/files.py", line 87, in save
setattr(self.instance, self.field.name, self.name)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/fields/files.py", line 311, in __set__
self.field.update_dimension_fields(instance, force=True)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/fields/files.py", line 381, in update_dimension_fields
width = file.width
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/core/files/images.py", line 17, in _get_width
return self._get_image_dimensions()[0]
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/core/files/images.py", line 27, in _get_image_dimensions
self.open()
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/fields/files.py", line 76, in open
self.file.open(mode)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/core/files/base.py", line 121, in open
if not self.closed:
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/core/files/base.py", line 59, in _get_closed
return not self.file or self.file.closed
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/storages/backends/s3boto.py", line 406, in _get_file
self.key.get_contents_to_file(self._file)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/boto/s3/key.py", line 1643, in get_contents_to_file
response_headers=response_headers)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/boto/s3/key.py", line 1475, in get_file
query_args=None)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/boto/s3/key.py", line 1529, in _get_file_internal
fp.write(bytes)
TypeError: string argument expected, got 'bytes'
model
class RequisitionImage(models.Model, ImageRisizeToolbox):
image_id = models.AutoField(primary_key=True)
requisition = models.ForeignKey(Requisition)
description = models.CharField(max_length=80)
image_file = models.ImageField(upload_to=get_file_path, height_field='image_height', width_field='image_width')
thumbnail_file = models.ImageField(upload_to=get_file_path, blank=True, null=True)
sort_order = models.SmallIntegerField(blank=True, null=True)
filetype = models.CharField(max_length=10, blank=True, null=True)
objects = models.Manager()
cust_objects = RequisitionImageManager()
MAX_SIZE = 4000000 # Image file size limit
def __str__(self):
return self.description
I am getting this error when i am trying to save the RequisitionImage object record both from the admin model and from my view.
So how to avoid this error and what is causing it ?
This is my first night playing around with Google App Engine with djangoforms rather than straight Django. I don't understand why this happens with db.DateTimeProperty().
import datetime
from google.appengine.ext import db
class BoringOldEvent(db.Model):
"""Models an individual Event that someone creates"""
creator = db.StringProperty()
date_created = db.DateTimeProperty(auto_now_add=True)
start_date_time = db.DateTimeProperty()
Will crash if start_date_time = db.DateTimeProperty() does not have auto_now_add=True.
I'm sure there is a good reason, but I"m left scratching my head at the moment because surely users expect to enter datetimes at some point....
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 187, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 225, in _LoadHandler
handler = __import__(path[0])
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 676, in Decorate
return func(self, *args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1858, in load_module
return self.FindAndLoadModule(submodule, fullname, search_path)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 676, in Decorate
return func(self, *args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1722, in FindAndLoadModule
description)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 676, in Decorate
return func(self, *args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1665, in LoadModuleRestricted
description)
File "/Users/mw/Documents/yayimin/main.py", line 8, in <module>
import events.views
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 676, in Decorate
return func(self, *args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1858, in load_module
return self.FindAndLoadModule(submodule, fullname, search_path)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 676, in Decorate
return func(self, *args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1722, in FindAndLoadModule
description)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 676, in Decorate
return func(self, *args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1665, in LoadModuleRestricted
description)
File "/Users/mw/Documents/yayimin/events/views.py", line 13, in <module>
class EventForm(djangoforms.ModelForm):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/db/djangoforms.py", line 772, in __new__
form_field = prop.get_form_field()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/db/djangoforms.py", line 353, in get_form_field
return super(DateTimeProperty, self).get_form_field(**defaults)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/db/djangoforms.py", line 200, in get_form_field
return form_class(**defaults)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_1_3/django/forms/fields.py", line 394, in __init__
super(DateTimeField, self).__init__(*args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_1_3/django/forms/fields.py", line 99, in __init__
widget = widget()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_1_3/django/forms/widgets.py", line 414, in __init__
self.format = formats.get_format('DATETIME_INPUT_FORMATS')[0]
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_1_3/django/utils/formats.py", line 67, in get_format
if use_l10n or (use_l10n is None and settings.USE_L10N):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_1_3/django/utils/functional.py", line 276, in __getattr__
self._setup()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_1_3/django/conf/__init__.py", line 40, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
INFO 2012-08-19 05:07:06,936 dev_appserver.py:2952] "GET /create/ HTTP/1.1" 500 -
Super duper thanks in advance!
It depends whether you're using Python 2.5 or 2.7. If you're using 2.7, you need to set the DJANGO_SETTINGS_MODULE variable in your app.yaml:
env_variables:
DJANGO_SETTINGS_MODULE: 'myapp.settings'
See the Django notes.