Hi Folks,
I'm having a devil of a time trying to get image uploading to work.
What I'd like to do is simply upload and image.
This works with:
my_object = ImageTest.objects.create()
...but if not with:
my_object = ImageTest.objects.get_or_create(user_id=7,
image=imagepath)
Any ideas?
Alternatively, if anyone out there has a *simple* example of how to
upload an image, I would appreciate knowing. Just want to get things
off the ground.
My views.py is below. (The model is a simple 2-field model w/t/fields
in question. "user_id" is not a Foreign Key to "User"). There is
some hard-coding as I'm just testing right now.
Thanks in advance for any help you can offer.
=====================
from PIL import Image
try:
import cStringIO as StringIO
except ImportError:
import StringIO
#from django import newforms as forms
from django import forms
from django.conf import settings
from models import ImageTest
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect
from django.views.generic.simple import direct_to_template
from django.core.urlresolvers import reverse
from django.template import RequestContext
from myproject.uploadtest.models import ImageTest
from django.core.files import File
import os
class ImageTestForm(forms.Form):
"""
Profile image upload form.
"""
image = forms.ImageField(widget=forms.FileInput())
def my_view(request):
if request.method == 'POST':
form = ImageTestForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_image(request.FILES['image'])
return HttpResponseRedirect('/')
else:
form = ImageTestForm()
return direct_to_template(request, 'uploadtest/image_upload.html',
{'image_upload_form': form})
def handle_uploaded_image(i):
# resize image
imagefile = StringIO.StringIO(i.read())
imageImage = Image.open(imagefile)
# (width, height) = imageImage.size
# (width, height) = imageImage.scale_dimensions(width, height,
longest_side=240)
width = 200
height = 200
resizedImage = imageImage.resize((width, height))
imagefile = StringIO.StringIO()
resizedImage.save(imagefile,'JPEG')
filename = 'foo5.jpg'
# #save to disk
imagefile = open(os.path.join('/tmp',filename), 'w')
resizedImage.save(imagefile,'JPEG')
imagefile = open(os.path.join('/tmp',filename), 'r')
content = File(imagefile)
path = 'img/testupload/2009/06/20/'
imagepath = path + filename
#my_object = ImageTest.objects.all()
#my_object = ImageTest.objects.get_or_create(user_id=7,
image=imagepath)
my_object = ImageTest.objects.create()
my_object.image.save(filename, content)
=====================
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---