2

我想根据 a 的值来获取 aCharField的值ImageField。我的表单和视图定义为:

#Form
class GpsImForm(forms.Form):
    image = forms.ImageField(required=True)
    gps_data = forms.CharField(required=True)

#View
def gpsim_gen_view(request):
    if request.method == 'POST':
        form = GpsImForm(request.POST, request.FILES)
        if 'image' in request.FILES:
            im = request.FILES['image']
            i = Image.open(im)
            ... # functions to extract exif data from i
            request.POST.update({ 'gps_data': ...}) # set gps_data based on exif data from i
        if form.is_valid():
            obj = form.save()
            return ... #returns the gpsim
    else:
        form = GpsImForm()
    return direct_to_template(request, 'gpsim_generate.html', {'form': form,})

gps_data更新,但是,一旦我使用Image.open(),我就会收到以下错误消息:

上传有效图片。您上传的文件不是图像或损坏的图像。

如果我评论有关的行i并将其修改gps_data为任何内容,则表单(带有图像)将被保存而没有任何错误......

# i = Image.open(im)
# ...
# functions to extract exif data from i
request.POST.update({ 'gps_data': 'some text'}) # set gps_data to 'test'
4

2 回答 2

2

首先,确保您的表单具有 enctype 标签

<form enctype="multipart/form-data" ... >    

尝试将 img(所有块)写入磁盘:

import Image
from random import choice
from django.conf import settings

random_file_name = getattr(settings, 'FILE_UPLOAD_TEMP_DIR', '/tmp')
random_file_name +=  '/' + ''.join([choice('abcdefg') for i in range(12)]) + '.jpg'

destination = open(random_file_name, 'wb+')
for chunk in request.FILES['image'].chunks():
    destination.write(chunk)
destination.close()

然后,您可以从磁盘打开它:

image = Image.open(random_file_name)
if image.mode != "RGB":
    image = image.convert("RGB")

...

此 URL 可以帮助您:

https://docs.djangoproject.com/en/dev/topics/http/file-uploads/

于 2012-09-20T16:21:28.383 回答
1

我终于找到了一个更干净的解决方案:我从我的模型中删除了“required=True”,并定义了一个 clean() 方法,它在我的表单模型中完成了这项工作:

#Form
class GpsImForm(forms.Form):
    image = forms.ImageField(required=True)
    gps_data = forms.CharField()

    def clean(self):
        super(forms.Form, self)).clean()
        if not self.cleaned_data['gps_data']:  # the user can provide the gps_data manually
            if self.cleaned_data['image']:     # if he provided no gps_data but an image
                i = Image.open(self.cleaned_data['image'])
                ... # functions to extract exif data from i
            else:
                msg = _("You have to provide an image or a gps_data.")
                self._errors['gps_data'] = self.error_class([msg]) 
        return self.cleaned_data


#View
def gpsim_gen_view(request):
    if request.method == 'POST':
        form = GpsImForm(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save()
            return ... #returns the gpsim
    else:
        form = GpsImForm()
    return direct_to_template(request, 'gpsim_generate.html', {'form': form,})
于 2012-09-21T08:51:57.003 回答