I am getting this traceback on my Apache2 server when trying to upload an image. I am using Python 3.5.2 and Pillow 5.0.0 and Django 2.1.1
I was able to upload images successfully when I am working on my localhost, but when I uploaded this code to the apache2 server, then it gives this traceback. Pillow is in the requiremnts.txt though. No where in the code do I explicitly try to import PIL, but it seems to be getting called.
I have tried installing Pillow and PIL. I have tried to uninstall PIL, uninstall Pillow, I have tried re-install both. Nothing seems to be working.
View.py
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.core import serializers
from manager.models import Manager, Inspection
from . import InspectorService
from . import InspectionService
import json
from .forms import InspectionImageForm
... more unrelevant code here ...
def upload_image(request):
if request.method == 'POST':
form = InspectionImageForm(request.POST, request.FILES)
inspection_id = request.POST.get('inspection_id')
if form.is_valid():
m = Inspection.objects.get(id = inspection_id)
m.image = form.cleaned_data['image']
m.save()
return JsonResponse({'error': False, 'message': 'Uploaded Successfully', 'location': m.image.name})
else:
return JsonResponse({'error': True, 'errors': form.errors})
else:
return JsonResponse({'error': True, 'errors': 'Post error'})
forms.py
from django import forms
class InspectionImageForm(forms.Form):
image = forms.ImageField()
inspection_id = forms.IntegerField()
Traceback
File "/opt/myenv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/opt/myenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "/opt/myenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/www/html/CMPUT401/computronix/manager/views.py" in upload_image
119. if form.is_valid():
File "/opt/myenv/lib/python3.5/site-packages/django/forms/forms.py" in is_valid
185. return self.is_bound and not self.errors
File "/opt/myenv/lib/python3.5/site-packages/django/forms/forms.py" in errors
180. self.full_clean()
File "/opt/myenv/lib/python3.5/site-packages/django/forms/forms.py" in full_clean
381. self._clean_fields()
File "/opt/myenv/lib/python3.5/site-packages/django/forms/forms.py" in _clean_fields
397. value = field.clean(value, initial)
File "/opt/myenv/lib/python3.5/site-packages/django/forms/fields.py" in clean
584. return super().clean(data)
File "/opt/myenv/lib/python3.5/site-packages/django/forms/fields.py" in clean
147. value = self.to_python(value)
File "/opt/myenv/lib/python3.5/site-packages/django/forms/fields.py" in to_python
613. from PIL import Image
Exception Type: ImportError at /manager/upload_image/
Exception Value: No module named 'PIL'
Related
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.
i followed this tutorial https://python.gotrained.com/scraping-telegram-group-members-python-telethon/, and the code ran successfully on a single python script. so i decided to implement the same code into django views.py. form.py, html templates and urls.py are properly connected. whenever i runserver and enter details it raises runtime error saying "There is no current event loop in thread 'Thread-1'."
views.py
import asyncio
from django.shortcuts import render,redirect
from telethon.sync import TelegramClient
from .form import DetailForm,CodeForm
from .models import Detail,Code
# Create your views here.
def home(request):
form = DetailForm
context = {'form':form}
if request.method=='POST':
form = DetailForm(request.POST)
if form.is_valid():
form.save()
details = Detail.objects.all().last()
api_id = int(details.api_id)
api_hash = details.api_hash
phone_number = details.phone_number
loop = asyncio.new_event_loop()
client = TelegramClient(phone_number, api_id, api_hash, loop=loop)
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone_number)
# global client, phone_number
return redirect('code')
return render(request, 'teleapp/home.html', context)
def codeview(request):
code=CodeForm
# codemodel = Code.objects.all().last()
if request.method == 'POST':
codes = CodeForm(request.POST)
if codes.is_valid():
codes.save()
#what next...
return redirect('scrapy')
context = {'code':code}
return render(request, 'teleapp/code.html', context)
def scrappy(request):
details = Detail.objects.all().last()
context = {'details':details}
return render(request, 'teleapp/scrappy.html', context)```
**error raised**
Internal Server Error: /
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\telegram\venv\lib\site-packages\django\c
ore\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\User\PycharmProjects\telegram\venv\lib\site-packages\django\c
ore\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\User\PycharmProjects\telegram\venv\lib\site-packages\django\c
ore\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\User\PycharmProjects\telegram\scrapy\teleapp\views.py", line
24, in home
client.connect()
File "C:\Users\User\PycharmProjects\telegram\venv\lib\site-packages\telethon
\sync.py", line 35, in syncified
loop = asyncio.get_event_loop()
File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\asyncio\ev
ents.py", line 694, in get_event_loop
return get_event_loop_policy().get_event_loop()
File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\asyncio\events.py", line 602, in get_event_loop
% threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-2'.
I'm using django 1.11 and i'm getting a tough time in storing a Json response.Here's my views.py code
views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .models import addinfomodels
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.core import serializers
import json
# Create your views here.
def addinfo(request):
batch_year = [2016, 2017, 2018]
dept = ['AERO', 'BME', 'CIVIL', 'CSE', 'ECE', 'EEE', 'E&I', 'MECH']
type = ['onecredit', 'core', 'professional', 'openelective']
return render(request, "cbcsportal/addinfo.html", {'type': type, 'batch': batch_year, 'dept': dept})
def rollvalue(request):
return request.POST.get('rollno')
# d ={}
def jsonvalue(request):
d = {"courses":[{"choices": [request.POST.get('choices00') ,request.POST.get('choices10')], "code": request.POST.get('code0'), "name": request.POST.get('name10')}]}
ds = serializers.serialize('json', d)
print ds
return JsonResponse(ds, content_type="application/json", safe=False)
def posttodb(request):
if request.method == "POST":
data = addinfomodels()
data.batch = request.POST.get('batch')
data.dept = request.POST.get('dept')
data.typeid = request.POST.get('typeid')
data.type = request.POST.get('type')
data.rollno = [rollvalue(request)]
data.renderJSON = jsonvalue(request)
data.starttime = request.POST.get('starttime0')
data.endtime = request.POST.get('endtime0')
data.save()
return redirect('addinfo')
please help me i'm getting this error
'unicode' object has no attribute '_meta'
this is the traceback
Traceback:
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\admin\Desktop\SREC_OBA\cbcsportal\views.py" in posttodb
34. data.renderJSON = jsonvalue(request)
File "C:\Users\admin\Desktop\SREC_OBA\cbcsportal\views.py" in jsonvalue
21. ds = serializers.serialize('json', d)
File "C:\Python27\lib\site-packages\django\core\serializers__init__.py" in serialize
129. s.serialize(queryset, **options)
File "C:\Python27\lib\site-packages\django\core\serializers\base.py" in serialize
84. concrete_model = obj._meta.concrete_model
Exception Type: AttributeError at /cbcs/posttodb
Exception Value: 'unicode' object has no attribute '_meta'
Here:
d = {....}
ds = serializers.serialize('json', d)
#print ds
return JsonResponse(ds, content_type="application/json", safe=False)
You are passing a dict to serialize(). Django serializer are for serializing django's orm querysets (this is documented, and you could gave found out by reading the traceback).
The proper way to serialize a python dict to json is quite simply to use json.dumps(yourdict). BUT : in your case this is useless anyway, since JsonResponse expects a python dict as first argument and will take care of the serialization. Also you don't need to set the content type, it's already the default for JsonResponse. IOW, all you need is:
d = {....}
return JsonResponse(d, safe=False)
As a side note: here:
def posttodb(request):
if request.method == "POST":
data = addinfomodels()
data.batch = request.POST.get('batch')
data.dept = request.POST.get('dept')
data.typeid = request.POST.get('typeid')
data.type = request.POST.get('type')
data.rollno = [rollvalue(request)]
data.renderJSON = jsonvalue(request)
data.starttime = request.POST.get('starttime0')
data.endtime = request.POST.get('endtime0')
data.save()
You're inserting data in your db that are unvalidated, unsanitized user inputs. DONT DO THAT !!! (unless you're happy to have your server hacked by the first script kiddie of course). Use Django forms (in this case ModelForm to take care of validation and sanitization.
I've implemented django-versatileimagefield and have gotten it to a state where I can successfully resize images in templates with the use of the following tag, for example:
As a result, I'm confident that my form.py, view.py, and template works. I have, however, recently tried to 'prewarm' the images so that when a user saves an image, a set of resized images are saved to my 'media' folder. This prevents the server from having to resize dynamically on every page load and can just grab the correctly sized image.
My problem is that when the user goes to save an image within the image upload form, they get an error.
Settings.py
VERSATILEIMAGEFIELD_SETTINGS = {
'cache_length': 2592000,
'cache_name': 'versatileimagefield_cache',
'jpeg_resize_quality': 70,
'sized_directory_name': '__sized__',
'filtered_directory_name': '__filtered__',
'placeholder_directory_name': '__placeholder__',
'create_images_on_demand': False,
'image_key_post_processor': None,
'progressive_jpeg': False
}
VERSATILEIMAGEFIELD_RENDITION_KEY_SETS = {
'image_gallery': [
('image_large', 'thumbnail__400x400'),
('image_small', 'thumbnail__900x900')
]
}
models.py
from django.db import models
from django.db.models.signals import post_save
from versatileimagefield.fields import VersatileImageField
from django.dispatch import receiver
from versatileimagefield.image_warmer import VersatileImageFieldWarmer
class ImageGallery(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
image = VersatileImageField('image_gallery', upload_to=upload_location)
def __str__(self):
return self.author.username
#receiver(models.signals.post_save, sender=ImageGallery)
def warm_gallery_images(sender, instance, **kwargs):
gallery_img_warmer = VersatileImageFieldWarmer(
instance_or_queryset=instance,
rendition_key_set='image_gallery',
image_attr='image_small'
)
num_created, failed_to_create = gallery_img_warmer.warm()
Traceback
Environment:
Traceback:
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "C:\Users\jason\Desktop\jason\accounts\views.py" in imagegallery
513. instance.save()
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py" in save
729. force_update=force_update, update_fields=update_fields)
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py" in save_base
769. update_fields=update_fields, raw=raw, using=using,
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\dispatch\dispatcher.py" in send
178. for receiver in self._live_receivers(sender)
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\dispatch\dispatcher.py" in <listcomp>
178. for receiver in self._live_receivers(sender)
File "C:\Users\jason\Desktop\jason\accounts\models.py" in warm_gallery_images
177. num_created, failed_to_create = gallery_img_warmer.warm()
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\versatileimagefield\image_warmer.py" in warm
143. reduce(getattr, self.image_attr.split("."), instance)
Exception Type: AttributeError at /accounts/profile/websitesetup5/upload/
Exception Value: 'ImageGallery' object has no attribute 'image_small'
I feel like I've followed the instructions on this page, but I'm still getting this error.
http://django-versatileimagefield.readthedocs.io/en/latest/improving_performance.html#turning-off-on-demand-image-creation
I should note that I do NOT have django REST framework installed. My understanding is that it's not required for this post-save method of prewarming images.
Thanks so much!
It looks like the image_attr field should point to the model field image:
#receiver(models.signals.post_save, sender=ImageGallery)
def warm_gallery_images(sender, instance, **kwargs):
gallery_img_warmer = VersatileImageFieldWarmer(
instance_or_queryset=instance,
rendition_key_set='image_gallery',
image_attr='image'
)
num_created, failed_to_create = gallery_img_warmer.warm()
I've been having a problem with a website that I'm working on not attaching pictures to html emails. Thought I had it fixed but then every time someone tries to register on it I get a Server Error (500). I've only changed a couple of references so no idea what went wrong there, anyways error log is as follows:
2016-08-31 08:26:15,757 :Internal Server Error: /register/
Traceback (most recent call last):
File "/home/asranet/.virtualenvs/testenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/asranet/.virtualenvs/testenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "./register/views.py", line 14, in index
form.save(commit=True)
File "/home/asranet/.virtualenvs/testenv/local/lib/python2.7/site-packages/django/forms/models.py", line 451, in save
self.instance.save()
File "./register/models.py", line 35, in save
email_client(self, site_settings.site_name + "Conference Registration", "You are officially registered for AdWind 2017")
File "./adWind/email_functionality.py", line 31, in email_client
fp = open(os.path.join(os.path.dirname(__file__), f), 'rb')
IOError: [Errno 2] No such file or directory: u'./adWind/static/Images/asranetLogo.jpg'
I checked and the file is there. No idea how to proceed, could really use some help. Thank you in advance!
P.S. here's the code for email functionality:
from __future__ import unicode_literals
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
import os
from email.mime.image import MIMEImage
from reportlab.platypus.doctemplate import SimpleDocTemplate
from reportlab.platypus import Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from django.http import HttpResponse
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
def email_client(self, subject, text):
# Send the client an email
html_content = render_to_string("../templates/baseTemplates/emailToUser.html", {'salutation': self.salutation,
'last_name':
self.last_name,
'text_body': text})
msg = EmailMultiAlternatives(subject, 'Dear ' + self.salutation + ' ' +
self.last_name + '/n' + text,
'adwind#asranet.co.uk', [self.email], )
msg.attach_alternative(html_content, "text/html")
msg.attach_file('/static/Images/asranetLogo.jpg')
msg.mixed_subtype = 'related'
f = '/static/Images/asranetLogo.jpg'
fp = open(os.path.join(os.path.dirname(__file__), f), 'rb')
msg_img = MIMEImage(fp.read())
fp.close()
msg_img.add_header('Content-ID', '<{}>'.format(f))
msg.attach(msg_img)
msg.send(fail_silently=True)
def email_admin(self, subject, text, sorted_self):
styleSheet = getSampleStyleSheet()
# Send the admin a PDF of client details
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="clientDetails.pdf"'
string_buffer = StringIO()
new_pdf = []
header = Paragraph("AdWind Attendee Details", styleSheet['Heading1'])
new_pdf.append(header)
for element in sorted_self:
new_pdf.append(Paragraph(element[0], styleSheet['Heading3']))
new_pdf.append(Paragraph(element[1], styleSheet['BodyText']))
new_pdf.append(Spacer(1, 2))
doc = SimpleDocTemplate(string_buffer)
doc.build(new_pdf)
pdf = string_buffer.getvalue()
string_buffer.close()
msg = EmailMultiAlternatives(subject, text, "adwind#asranet.co.uk", ["adwind#asranet.co.uk"])
msg.attach(self.first_name + self.last_name + "adWind.pdf", pdf, "application/pdf")
msg.send(fail_silently=True)
In Django the static directory is usually under a module_name directory. I suggest changing your paths into a relative one:
msg.attach_file('static/[module_name]/Images/asranetLogo.jpg')
and
f = 'static/[module_name]/Images/asranetLogo.jpg'