如果我的模型中有多个字段而不是文件字段,则无法上传文件。我没有在页面上收到任何错误,但页面只是显示相同的页面而没有上传我的图像。
这是我的模特
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
答案 0 :(得分:1)
只需在视图中添加一个else块即可进行表单验证。我认为您的表单无效,并且您不只是在模板中打印任何错误。
if form.is_valid():
newdoc = ImageUpload(imagefile = request.FILES['imagefile'])
newdoc.save()
else:
# do something visible here
此外,如果您的表单有效,则可以使用form.save()
保存图片和相关数据,而不是创建新的ImageUpload
对象。
此外,您的模型需要保存User
对象。