图像上传不在Django中保存文件

时间:2014-06-26 18:32:06

标签: python django

点击上传时没有错误。但是图像并没有出现在我指出它应该出现的地方。在MEDIA_ROOT中放置一个绝对路径,并在(upload_to)param ImageField中引用相同的路径。不确定我错过了什么。

型号:

class FileUploadHandler(models.Model):
    title = models.CharField(max_length=100)
    file = models.ImageField(upload_to='/Python27/Lib/site-packages/django/bin/mideastinfo/wiki/static/')

查看:

from models import Article, Edit
from forms import ArticleForm, EditForm
from forms import *
from PIL import Image
from models import FileUploadHandler

def image_upload(request):
    if request.method == 'POST':
        form = UploadImageForm(request.POST, request.FILES)
        if form.is_valid():
            FileUploadHandler(request.FILES['image'])
            return render_to_response('wiki/gallery.html')
    else:
        form = UploadImageForm()
    return render_to_response('wiki/gallery.html', RequestContext(request, {'form': form}))

Forms.py:

class UploadImageForm(forms.ModelForm):
    class Meta:
    model = FileUploadHandler
    #image = forms.ImageField()\
    fields = ['title']

3 个答案:

答案 0 :(得分:0)

此处您没有将其保存在视图中。只需使用:

 if request.method == 'POST':
    form = UploadImageForm(request.POST, request.FILES)
    if form.is_valid():
        newfile = FileUploadHandler(title='anything', file=request.FILES['image'])
        newfile.save()

答案 1 :(得分:0)

我认为你的工作有点太难了。您不必直接调用FileUploadHandler模​​型来保存图像。

首先,您的表单应为:

class UploadImageForm(forms.ModelForm):
    class Meta:
        model = FileUploadHandler

你的观点应该是:

from forms import UploadImageForm

def image_upload(request):
    form = UploadImageForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()
    return render_to_response('wiki/gallery.html', RequestContext(request, {'form': form}))

由于您使用的是ModelForm,因此只需在验证后保存表单即可。只需确保文件字段在模板中可见。您排除了'文件'您之前的格式中的字段,这就是它无法正常工作的原因。

更新:简化您的观点,因为......

答案 2 :(得分:0)

解决方案可能是模板:

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form }}
    <input type="submit" name="submit" value="Submit" />
</form>

通知: enctype="multipart/form-data"