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

发布于 2024-11-08 17:07:38 字数 2410 浏览 0 评论 0原文

我很努力,但我没能成功。我正在尝试找到一种用户如何使用 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)

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

我做错了什么?

I tried hard, but I couldn't make it. I am trying to find a way on how a user can upload its avatar image, using django and this is my code:

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)

With this code, the field in the database is inserted as the path of the saved image, correctly (although just the name of the image-file would be enough) but the image is not saved where it is supposed to be saved or not saved at all (I can't be sure if the file is stored somewhere else that is why I am saying this -- though I checked)
any more code will be added if requested.

What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤城病女 2024-11-15 17:07:38

希望我的建议对您有帮助

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()

Hope my suggestion be helpful for you

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()
-残月青衣踏尘吟 2024-11-15 17:07:38

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

'/site_media/...'

You might want to doublecheck the opening slash in your paths (I assume you don't actually want to save images in the root of your file system.)

i.e.

'/site_media/...'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文