0

如果我的模型中有多个字段而不是文件字段,我将无法上传文件。我在页面上没有收到任何错误,但页面只是显示相同的页面而没有上传我的图像。

这是我的模型

class ImageUpload(models.Model):
   username = models.ForeignKey(User)
   imagefile = models.FileField(upload_to='pictures')
   isapproved = models.BooleanField()
   class Meta:
       db_table = u'imageupload'

   def __unicode__(self):
       return u'%s' % (self.imagefile)

这是我的模型表格

class UploadImageForm(forms.ModelForm):
   def __init__(self,user, *args, **kwargs):
       super(UploadImageForm, self).__init__(*args, **kwargs)
       self.fields['username'] = forms.CharField(initial = user,
                                       widget = forms.TextInput(
                                     attrs = {'readonly':'readonly'}))
   class Meta:
       model = ImageUpload
       exclude = ('id', 'isapproved')

这是我处理数据的观点。

def imageupload(request):
# Handle file upload
   if request.method == 'POST':
      list = ["jpeg", "jpg","JPG","JPEG","png","PNG"]
      format = imghdr.what(request.FILES['imagefile'])
      if format not in list:
          error = "Please upload a valid file format"
          form = UploadImageForm(request.user)
          return HttpResponseRedirect(reverse('myview.views.imageupload'))
      else:
          form = UploadImageForm(request.POST, request.FILES)
          if form.is_valid():
              newdoc = ImageUpload(imagefile = request.FILES['imagefile'])
              newdoc.save()
          return HttpResponseRedirect(reverse('myview.views.imageupload'))
  else:
      form = UploadImageForm(request.user) # A empty, unbound form
  documents = ImageUpload.objects.all()
  return render_to_response('imageupload.html',
       {'documents': documents, 'form': form,'media':settings.MEDIA_URL},
        context_instance=RequestContext(request)
   )

当我只使用模型表单中的文件字段时,它曾经正常工作。向模型添加更多字段后,它不会上传文件。有关如何解决此问题的任何建议?

提前致谢 Vikram

4

1 回答 1

1

只需在视图中添加一个 else 块以进行表单验证。我认为您的表格无效,您不只是在模板中打印任何错误。

if form.is_valid():
    newdoc = ImageUpload(imagefile = request.FILES['imagefile'])
    newdoc.save()
else:
    # do something visible here

此外,如果您的表单有效,您可以只使用form.save()保存图像和相关数据而不是创建新ImageUpload对象。

此外,您的模型需要User保存对象。

于 2012-10-14T01:19:40.760 回答