保存到Django ImageField

时间:2013-12-31 17:52:20

标签: django django-models

我正在使用jcrop进行裁剪和图像,然后我想保存到ImageField。

我已使用下面的代码成功保存到我网站其他部分的ImageField,但在这个例子中我收到以下错误消息:

'NoneType' object has no attribute 'rfind'

我的观点

def archive_update_profile_photo(request, id, slug):

    photo_to_crop_from= Media.objects.get(id=2)

    form = CropForm()
    if request.method == 'POST':
        form = CropForm(request.POST)
        if form.is_valid():
            x = form.cleaned_data['x']
            y = form.cleaned_data['y']
            w = form.cleaned_data['w']
            h = form.cleaned_data['h']
            print x, y, w, h

            selected_media= Media.objects.get(id=2)

            raw_image = Image.open(selected_media.diplay_photo)

            # crop here
            l = x
            t = y
            r = x + w
            b = y + h
            cropped_image = raw_image.crop((l, t, r, b))

            # resize here
            profile_image = cropped_image.resize((150, 150), Image.ANTIALIAS)


            profile_image.show()

            legacy = Legacy.objects.get(id=id)

            #save the profile image
            temp_handle = StringIO()
            profile_image.save(temp_handle, 'jpeg')
            temp_handle.seek(0)
            #save  profile image to imagefield
            suf = SimpleUploadedFile(os.path.split(legacy.legacy_profile_image.name)[-1].split('.')[0], temp_handle.read(), content_type='image/jpeg')
            legacy.legacy_profile_image.save('%s.jpg' % suf.name, suf, save=True)

            return HttpResponseRedirect(reverse('archive_legacy', args=(id,slug)))

    return render(request, 'archive_app/archive_update_profile_photo.html', {'form': form,'photo_to_crop_from':photo_to_crop_from})

我的模特

def get_legacy_profile_image_name(request, instance):
    return 'profile_images/%s__%s' % (str(time()).replace('.','-'), 'legacy_profile_image')

class Legacy(models.Model):
    created_date = models.DateTimeField(default=datetime.now)
    legacy_profile_image = models.ImageField(upload_to=get_legacy_profile_image_name, blank=True, null=True)

引用

Environment:


Request Method: POST
Request URL: http://localhost:8000/archive/update/profile/image/5/Virginia-Meeks/

Django Version: 1.5.4
Python Version: 2.7.1
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django.contrib.humanize',
 'bootstrap_toolkit',
 'longerusername',
 'south',
 'storages',
 'boto',
 'archive')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/Users/bbrooke/Code/yourlegacy/env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Users/bbrooke/Code/yourlegacy/env/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  25.                 return view_func(request, *args, **kwargs)
File "/Users/bbrooke/Code/yourlegacy/archive/views.py" in archive_update_profile_photo
  500.          suf = SimpleUploadedFile(os.path.split(legacy.legacy_profile_image.name)[-1].split('.')[0], temp_handle.read(), content_type='image/jpeg')
File "/Users/bbrooke/Code/yourlegacy/env/bin/../lib/python2.7/posixpath.py" in split
  83.     i = p.rfind('/') + 1

Exception Type: AttributeError at /archive/update/profile/image/5/Virginia-Meeks/
Exception Value: 'NoneType' object has no attribute 'rfind'

我非常感谢您的反馈和专业知识

1 个答案:

答案 0 :(得分:2)

legacy.legacy_profile_image.nameNone。这可能会发生,因为legacy_profile_image可以为空。因此,您可能希望在那里添加None支票。

此外,您的upload_to方法get_legacy_profile_image_name有点破碎;传递的参数是instance and filename,而不是requestinstance。这并不重要,因为你不使用参数......