django:放弃用户上传其头像。图像未存储。需要帮忙!

时间:2011-05-19 07:57:33

标签: django image file-upload

我努力了,但我做不到。我试图找到一个方法,用户可以使用django上传其头像图像,这是我的代码:

settings.py

USER_IMAGE_PATH = '/site_media/user_data/images/'

models.py

fs = FileSystemStorage(location=settings.USER_IMAGE_PATH)

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    avatar = models.ImageField(storage=fs, upload_to=settings.USER_IMAGE_PATH)

forms.py

class ProfileForm(forms.Form):
    avatar = forms.ImageField(label='avatar', required=False)

urls.py

(r'^profile/(\w+)/$', profile_form),

views.py

@login_required
def profile_form(request, username):
    form = ProfileForm(request.POST, request.FILES)
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        raise Http404(u'User not Found')
    if form.is_valid():
        avatar = form.cleaned_data['avatar']
        profile = user.get_profile()
        profile.avatar = avatar
        if not avatar:
            pass
        else:
            image_file = request.FILES['avatar']
            im = imageilb()
            filename, content = im.handle_uploaded_image(image_file)
            profile.avatar.save(filename, content)

imagelib.handle_uploaded_image()

import hashlib
from PIL import Image
import os.path
import StringIO
import django

def handle_uploaded_image(self,i):
    # resize image
    imagefile  = StringIO.StringIO(i.read())
    imageImage = Image.open(imagefile)

    (width, height) = imageImage.size
    (width, height) = self.scale_dimensions(width, height, longest_side=240)

    resizedImage = imageImage.resize((width, height))

    imagefile = StringIO.StringIO()
    resizedImage.save(imagefile,'JPEG')
    filename = hashlib.md5(imagefile.getvalue()).hexdigest()+'.jpg'

    # #save to disk - hardcoding of paths will be removed as soon as this thing works
    imagefile = open(os.path.join('/site_media/user_data/images',filename), 'w')
    resizedImage.save(imagefile,'JPEG')
    imagefile = open(os.path.join('/site_media/user_data/images',filename), 'r')
    return filename, django.core.files.File(imagefile)

使用此代码,数据库中的字段将作为已保存图像的路径正确插入(虽然只是图像文件的名称就足够了)但图像不会保存在应该保存的位置或者根本没有保存(我无法确定文件是否存储在其他地方,这就是我说这个的原因 - 虽然我查了一下) 如果需要,将添加更多代码。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

希望我的建议对你有所帮助

settings.py

USER_IMAGE_PATH = '/site_media/user_data/images/'

models.py

fs = FileSystemStorage(location=settings.USER_IMAGE_PATH)
class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    avatar = models.ImageField(storage=fs, upload_to='avatar')

    def save(self, *args, **kwargs):
       super(UserProfile, self).save(*args, **kwargs)
       if self.avatar:
           imglib.resize_image(avatar)

imglib.py

from PIL import Image

def resize_image(avatar, size=(200,200)):
    image = Image.open(avatar.path)
    image.resize(size, Image.ANTIALIAS).save(avatar.path, 'JPEG', quality=75)

views.py

@login_required
def profile_form(request, username):
    form = ProfileForm(request.POST, request.FILES)
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        raise Http404(u'User not Found')
    if form.is_valid():
        avatar = form.cleaned_data['avatar']
        profile = user.get_profile()
        profile.avatar = avatar
        profile.save()

答案 1 :(得分:0)

您可能想要仔细检查路径中的左侧斜线(我假设您实际上并不想将图像保存在文件系统的根目录中。)

'/site_media/...'