Pillow on Heroku doesn't work - django

I'm developing an application with Django1.4.3 and Pillow2.0.0.
I have a form to upload image file.
After resizing and cropping posted image file,
I want to save the image file, but error occur.
In django's local test server, error doesn't occur and work well,
but in Heroku, error occur.
Would you tell me some advice?
The code receiving posted image is below.
In addition, I use S3boto and django-storage.
def edit_photo(request):
if request.user.is_authenticated():
if request.method == 'POST':
# save posted image as UserProfile.image temporarily
posted_photo = request.FILES['posted_photo']
file_content = ContentFile(posted_photo.read())
profile = request.user.get_profile()
temp_filename = "new_file_"+str(profile.id)+"_"+posted_photo.name
profile.image.save(temp_filename, file_content)
# read posted file
data = profile.image.read()
im = Image.open(StringIO.StringIO(data))
# crop posted image
cropping_box = (10, 10, 300, 300)
photo = photo.crop(cropping_box)
photo_comp = photo.resize((230, 230), Image.ANTIALIAS)
# save the image
thum = StringIO.StringIO()
photo_comp.save(thum, "png")
profile.image.save("saved_image_"+str(profile.id)+".png",ContentFile(thum.getvalue()))
# delete temporary image
default_storage.delete("faces/"+temp_filename)
return redirect('../')
And Error message is like this.
TypeError at /manage/edit_photo
function takes at most 4 arguments (6 given)
Request Method: POST
Request URL: http://hogehoge.herokuapp.com/manage/edit_photo
Django Version: 1.4.3
Exception Type: TypeError
Exception Value:
function takes at most 4 arguments (6 given)
Exception Location: /app/.heroku/python/lib/python2.7/site-packages/PIL/Image.py in _getencoder, line 395
Python Executable: /app/.heroku/python/bin/python
Python Version: 2.7.4
Python Path:
['/app',
'/app/.heroku/python/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg',
'/app/.heroku/python/lib/python2.7/site-packages/newrelic-1.11.0.55/newrelic/bootstrap',
'/app',
'/app/.heroku/python/lib/python27.zip',
'/app/.heroku/python/lib/python2.7',
'/app/.heroku/python/lib/python2.7/plat-linux2',
'/app/.heroku/python/lib/python2.7/lib-tk',
'/app/.heroku/python/lib/python2.7/lib-old',
'/app/.heroku/python/lib/python2.7/lib-dynload',
'/app/.heroku/python/lib/python2.7/site-packages',
'/app/.heroku/python/lib/python2.7/site-packages/PIL',
'/app/.heroku/python/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg-info']
/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py in get_response
response = callback(request, *callback_args, **callback_kwargs) ...
▶ Local vars
/app/movie_manager/views.py in edit_photo
photo_comp.save(thum, "png") ...
▶ Local vars
/app/.heroku/python/lib/python2.7/site-packages/PIL/Image.py in save
save_handler(self, fp, filename) ...
▶ Local vars
/app/.heroku/python/lib/python2.7/site-packages/PIL/PngImagePlugin.py in _save
ImageFile._save(im, _idat(fp, chunk), [("zip", (0,0)+im.size, 0, rawmode)]) ...
▶ Local vars
/app/.heroku/python/lib/python2.7/site-packages/PIL/ImageFile.py in _save
e = Image._getencoder(im.mode, e, a, im.encoderconfig) ...
▶ Local vars
/app/.heroku/python/lib/python2.7/site-packages/PIL/Image.py in _getencoder
return encoder(mode, *args + extra) ...
▶ Local vars

For anyone else who finds this problem...
This TypeError can occur when PIL and Pillow are installed simultaneously (perhaps inadvertently due to hidden package requirements). You'll need to uninstall both PIL and Pillow and reinstall just the one you want.

Related

How Can I upload All types of files (videos, audios, pdfs, zip) in cloudinary in django model ? and how can i delete them?

models.py
from django.db import models
from cloudinary.models import CloudinaryField
class File(models.Model):
caption = models.TextField(blank=True)
file = CloudinaryField()
# trying to delete the File model and cloudinary file (error)
def delete(self, *args, **kwargs):
self.file.delete(*args, **kwargs)
super().delete(*args, **kwargs)
settings.py
import cloudinary
import cloudinary.uploader
import cloudinary.api
...
INSTALLED_APPS = [
'....',
'myapp',
'cloudinary',
]
...
cloudinary.config(
cloud_name = "...",
api_key = "...",
api_secret = "...",
secure = True
)
i can upload images only, when i try to upload any (video, pdf, audio, zip) it says INVALID IMAGE FILE.
and sometimes file size error occurs when image size exceeds 10 mb size limit.
This is The Error i am facing. (when i tried to upload a video file)
Error at /
Invalid image file
Request Method: POST
Request URL: http://127.0.0.1:8000/
Django Version: 3.2.9
Exception Type: Error
Exception Value:
Invalid image file
Exception Location: C:\Users\MIG 29\Desktop\Project\testCloudinary\vEnv\lib\site-packages\cloudinary\uploader.py, line 522, in call_api
Python Executable: C:\Users\MIG 29\Desktop\Project\testCloudinary\vEnv\Scripts\python.exe
Python Version: 3.9.6
Python Path:
['C:\\Users\\MIG 29\\Desktop\\Project\\testCloudinary',
'c:\\users\\mig 29\\appdata\\local\\programs\\python\\python39\\python39.zip',
'c:\\users\\mig 29\\appdata\\local\\programs\\python\\python39\\DLLs',
'c:\\users\\mig 29\\appdata\\local\\programs\\python\\python39\\lib',
'c:\\users\\mig 29\\appdata\\local\\programs\\python\\python39',
'C:\\Users\\MIG 29\\Desktop\\Project\\testCloudinary\\vEnv',
'C:\\Users\\MIG '
'29\\Desktop\\Project\\testCloudinary\\vEnv\\lib\\site-packages']
Server time: Sun, 05 Dec 2021 06:14:04 +0000
thank me, i just found the way to upload (images, videos, audios) too..
it goes like this.
in models.py
file = CloudinaryField(resource_type='')
This comes many months later, but I hope it helps someone out there.
So, in addition to the above answer, you can upload various file types by setting the resource type in your model field to:
image
video
raw or
auto
For example:
file = CloudinaryField(resource_type='raw')
I'm not sure how to delete the uploaded resource from the server-side, if that's what the second part of the inquiry was asking.
This resource: Upload API Reference | Cloudinary helped me.

Unable to perform conditional redirect from a class based view Django

I am trying to redirect a user who has already registered to a different view. here is the code for the views.py
However when qs.exists() = true I get an error
'The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.'
I am a beginner have read the documentation but unable to find where i am going worng.
Thanks
from django.shortcuts import render, redirect
from django.views import View
from Lpage.forms import SubscriberEntryForm
from Lpage.models import Subscriber
class homeview(View):
def get(self,request):
msg = request.session.get('msg', False)
if(msg):
del(request.session['msg'])
return render(request,'Lpage/index.html')
def post(self, request):
form = SubscriberEntryForm(request.POST or None)
if form.is_valid():
obj = form.save(commit=False)
qs = Subscriber.objects.filter(email__iexact=obj.email)
if qs.exists():
return redirect('messageview')
else:
obj.save()
request.session['msg'] = "msg"
return redirect(request.path)
def messageview(request):
return render(request,'Lpage/messages.html',{})
Here is the error message
ValueError at /
The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.
Request Method: POST
Request URL: http://localhost:8000/
Django Version: 3.2.7
Exception Type: ValueError
Exception Value:
The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.
Exception Location: C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 309, in check_response
Python Executable: C:\Users\Ganesamurthi\anaconda3\python.exe
Python Version: 3.8.5
Python Path:
['D:\dreamdoors\dd',
'C:\Users\Ganesamurthi\anaconda3\python38.zip',
'C:\Users\Ganesamurthi\anaconda3\DLLs',
'C:\Users\Ganesamurthi\anaconda3\lib',
'C:\Users\Ganesamurthi\anaconda3',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\win32',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\win32\lib',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\Pythonwin']
Server time: Wed, 29 Sep 2021 05:23:43 +0000
Traceback Switch to copy-and-paste view
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\exception.py, line 47, in inner
response = get_response(request) …
▶ Local vars
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 188, in _get_response
self.check_response(response, callback) …
▶ Local vars
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 309, in check_response
raise ValueError( …
▶ Local vars
redirect expects you to pass a URL but you gave it messageview, which is a view class in fact.
So you need to give redirect to the URL of messageview.

How to choose a Wagtail image across a ParentalManyToManyField?

Environment:
Wagtail 1.13
Django Version: 1.11.11
Python Version: 2.7.12
I'm following the Wagtail documentation to try to add an image showcase (not a category) to a page using ParentalManyToManyField:
class HomePage(Page):
showcase_title = models.CharField(max_length=100, blank="true", default="SHOWCASE")
showcase_images = ParentalManyToManyField('wagtailimages.Image')
content_panels = Page.content_panels + [
FieldPanel('showcase_title'),
InlinePanel('showcase_images', label="Showcase images", panels=[
ImageChooserPanel('showcase_images')
]),
]
Everything is fine if I comment out the showcase_images editing panel, but I get a KeyError as soon as uncomment the panel showcase_images. In addition to the above variation of editing showcase_images, I've also tried simply InlinePanel('showcase_images'), FieldPanel('showcase_images'), InlinePanel('showcase_images', label="Showcase images", panels=[ImageChooserPanel('image')]), and probably another variation or two. Can someone propose a solution?
Environment:
Request Method: GET
Request URL: http://dev.somedomain.com:8181/admin/pages/3/edit/
Django Version: 1.11.11
Python Version: 2.7.12
Installed Applications:
[u'my_app',
u'search',
u'wagtail.wagtailforms',
u'wagtail.wagtailredirects',
u'wagtail.wagtailembeds',
u'wagtail.wagtailsites',
u'wagtail.wagtailusers',
u'wagtail.wagtailsnippets',
u'wagtail.wagtaildocs',
u'wagtail.wagtailimages',
u'wagtail.wagtailsearch',
u'wagtail.wagtailadmin',
u'wagtail.wagtailcore',
u'wagtail.contrib.wagtailstyleguide',
u'modelcluster',
u'taggit',
u'wagtailfontawesome',
u'django.contrib.admin',
u'django.contrib.auth',
u'django.contrib.contenttypes',
u'django.contrib.sessions',
u'django.contrib.messages',
u'django.contrib.staticfiles']
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',
u'django.middleware.security.SecurityMiddleware',
u'wagtail.wagtailcore.middleware.SiteMiddleware',
u'wagtail.wagtailredirects.middleware.RedirectMiddleware']
Traceback:
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/django/views/decorators/cache.py" in _cache_controlled
43. response = viewfunc(request, *args, **kw)
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/wagtail/wagtailadmin/urls/__init__.py" in wrapper
96. return view_func(request, *args, **kwargs)
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/wagtail/wagtailadmin/decorators.py" in decorated_view
31. return view_func(request, *args, **kwargs)
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/wagtail/wagtailadmin/views/pages.py" in edit
481. edit_handler = edit_handler_class(instance=page, form=form)
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/wagtail/wagtailadmin/edit_handlers.py" in __init__
269. self.children.append(child(instance=self.instance, form=self.form))
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/wagtail/wagtailadmin/edit_handlers.py" in __init__
269. self.children.append(child(instance=self.instance, form=self.form))
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/wagtail/wagtailadmin/edit_handlers.py" in __init__
693. self.formset = form.formsets[self.__class__.relation_name]
Exception Type: KeyError at /admin/pages/3/edit/
Exception Value: u'showcase_images'
InlinePanel doesn't work with ParentalManyToManyField relations, only ParentalKey relations. You'll need to set up an intermediate model to define the relation between pages and images, like BlogPageGalleryImage in the tutorial's 'images' section (but with the caption field omitted in this case, so it's just a direct association between pages and images).
(Alternatively, you can use a plain FieldPanel with ParentalManyToManyField, but this will just give you a set of checkboxes for all images in the system, rather than the the image chooser interface.)

Django Create Account ends in 550

on a Django application (geonode 2.4) I´m trying to register a new user: me#gmail.com. This ends in ERROR SMTPRecipientsRefused sombody#yahoo.com (550, unknown User).
The same Setup works on a local vm (with same SMTP server)!
SETUP
Ubuntu 14.04
Django 1.6.11
Accounts App: geonode-user-accounts
(Forked from pinax-django-user-accounts)
SMTP local_settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_USE_SSL = True
EMAIL_HOST = 'mail.example.com'
EMAIL_HOST_USER = 'user#mail.example.com'
EMAIL_HOST_PASSWORD = 'pass'
EMAIL_PORT = 25 ## tested telnet to 587 but it seems only 25 is open
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
THEME_ACCOUNT_CONTACT_EMAIL = 'admin#example.com'
QUESTION
What I do not understand why does Django complain about sombody#yahoo.com when I try to register me#gmail.com? – It should not care about already registered users. How can I debug this?
TRACEBACK
SMTPRecipientsRefused at /account/signup/
{u'sombody#yahoo.com': (550, 'Unknown user')}
Request Method: POST
Request URL: http://geonode.barbatti.org/account/signup/
Django Version: 1.6.11
Exception Type: SMTPRecipientsRefused
Exception Value:
{u'max.muster#barbatti.de': (550, 'Unknown user')}
Exception Location: /usr/lib/python2.7/smtplib.py in sendmail, line 747
Python Executable: /usr/bin/python
Python Version: 2.7.6
Python Path:
['/var/www/geonode',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PILcompat',
'/usr/lib/pymodules/python2.7',
'/var/www']
Server time: Tue, 16 May 2017 09:52:13 -0500
Traceback Switch to copy-and-paste view
/usr/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/views/generic/base.py in view
return self.dispatch(request, *args, **kwargs) ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/views/generic/base.py in dispatch
return handler(request, *args, **kwargs) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/account/views.py in post
return super(SignupView, self).post(*args, **kwargs) ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/views/generic/edit.py in post
return self.form_valid(form) ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/account/views.py in form_valid
notification.send(staff, "account_approve", {"from_user": self.created_user}) ...
▶ Local vars
/usr/lib/python2.7/dist-packages/notification/models.py in send
return send_now(*args, **kwargs) ...
▶ Local vars
/usr/lib/python2.7/dist-packages/notification/models.py in send_now
backend.deliver(user, sender, notice_type, extra_context) ...
▶ Local vars
/usr/lib/python2.7/dist-packages/notification/backends/email.py in deliver
send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [recipient.email]) ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/core/mail/__init__.py in send_mail
connection=connection).send() ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/core/mail/message.py in send
return self.get_connection(fail_silently).send_messages([self]) ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/core/mail/backends/smtp.py in send_messages
sent = self._send(message) ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/core/mail/backends/smtp.py in _send
self.connection.sendmail(from_email, recipients, message.as_bytes()) ...
▶ Local vars
/usr/lib/python2.7/smtplib.py in sendmail
raise SMTPRecipientsRefused(senderrs) ...
I found it, what happens here is that
ACCOUNT_APPROVAL_REQUIRED = True
is set. The mentioned yahoo adress is an admin, which should be informed for approval. The Smtp is refusing the adress and throwing the 550.

Error using ModelResource: can't set attribute

I can't get my head around this error... I'm using the restframework2 branch.
Am I doing something wrong, or is this a bug in the restframework2 code?
Here's my code:
resources.py
class TemplateHoursSerializer(serializers.ModelSerializer):
class Meta:
model = TemplateHours
nested = True
start = HourField()
end = HourField()
employee = EmployeeSerializer()
class TemplateHoursResource(ModelResource):
model = TemplateHours
serializer_class = TemplateHoursSerializer
urls.py
url(r'^api/template-hours/$', TemplateHoursResource.as_view(actions={
'get': 'list',
'post': 'create'
})),
url(r'^api/template-hours/(?P<pk>[0-9]+)/$', TemplateHoursResource.as_view(actions={
'get': 'retrieve',
'put': 'update',
'delete': 'destroy'
})),
...
When I visit (or POST to) http://127.0.0.1:8000/api/template-hours/, I get this error and traceback:
AttributeError at /api/template-hours/
can't set attribute
Request Method: GET
Request URL: http://127.0.0.1:8000/api/template-hours/
Django Version: 1.4.1
Exception Type: AttributeError
Exception Value:
can't set attribute
Exception Location: C:\Users\Mathieu\Development\django_projects\hedron\Lib\site- packages\rest_framework\resources.py in wrapped, line 13
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
Python Path:
['C:\\Users\\Mathieu\\Development\\django_projects\\hedron\\Scripts',
'C:\\Python27\\lib\\site-packages\\setuptools-0.6c12dev_r88846-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\virtualenv-1.7.1.2-py2.7.egg',
'C:\\Users\\Mathieu\\Development\\django_projects\\hedron\\Lib\\site-packages',
'C:\\Users\\Mathieu\\Development\\django_projects\\hedron\\hedron',
'C:\\Python27\\python27.zip',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
path(u'C:\\Users\\Mathieu\\Development\\django_projects\\hedron'),
path(u'C:\\Users\\Mathieu\\Development\\django_projects\\hedron\\hedron\\apps'),
path(u'C:\\Users\\Mathieu\\Development\\django_projects\\hedron\\hedron\\libs')]
Server time: di, 9 Okt 2012 22:46:50 +0200
Traceback:
File "C:\Users\Mathieu\Development\django_projects\hedron\Lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Mathieu\Development\django_projects\hedron\Lib\site-packages\rest_framework\resources.py" in view
48. return self.dispatch(request, *args, **kwargs)
File "C:\Users\Mathieu\Development\django_projects\hedron\Lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
77. return view_func(*args, **kwargs)
File "C:\Users\Mathieu\Development\django_projects\hedron\Lib\site-packages\rest_framework\views.py" in dispatch
324. response = self.handle_exception(exc)
File "C:\Users\Mathieu\Development\django_projects\hedron\Lib\site-packages\rest_framework\views.py" in dispatch
321. response = handler(request, *args, **kwargs)
File "C:\Users\Mathieu\Development\django_projects\hedron\Lib\site-packages\rest_framework\resources.py" in list
74. return self.root_view().list(request, args, kwargs)
File "C:\Users\Mathieu\Development\django_projects\hedron\Lib\site-packages\rest_framework\resources.py" in root_view
68. return wrapped(self, self.root_class())
File "C:\Users\Mathieu\Development\django_projects\hedron\Lib\site-packages\rest_framework\resources.py" in wrapped
13. setattr(dest, attr, getattr(source, attr))
Exception Type: AttributeError at /api/template-hours/
Exception Value: can't set attribute
Resources and routers are not finished/supported in [the beta of] REST framework 2 yet. The docs on them are a placeholder for what I want the design to look like, but I'll be removing them from the index today. Hopefully they'll make it in for 2.0, but I don't see it as at all essential, since you can do everything you need with Views and explicit URLconfs. Resources & routers just give you a useful shortcut.