我有一个上传表单,允许用户上传照片,word文档或两者。我需要逻辑方面的帮助,以便只要他们有一张照片或选择上传的文件,表格就有效,上传也会有效。当我同时拥有照片和文档时,它总是有效,但当它只是一张照片或文档时,它似乎随机工作。这是我目前的代码:
def upload(request):
"""
Uploads document/photo
"""
if request.method == 'POST':
form1 = DocumentForm(request.POST, request.FILES)
form2 = PhotoForm(request.POST, request.FILES)
if form1.is_valid() and form2.is_valid() :
post1 = Document(user = request.user, document= form1.cleaned_data['document'], title = form1.cleaned_data['title'])
post1.save()
post2 = Photo(user = request.user, alias = request.user.username, img = form2.cleaned_data['img'], title = "")
post2.save()
return HttpResponse(template.Template('''
<html><head><title>Uploaded</title></head> <body>
<h1>Uploaded</h1>
</body></html>
'''
).render( template.Context({}))
)
elif form1.is_valid():
post1 = Document(user = request.user, document = form1.cleaned_data['document'], title = form1.cleaned_data['title'])
post1.save()
return HttpResponse(template.Template('''
<html><head><title>Uploaded</title></head> <body>
<h1>Uploaded</h1>
</body></html>
'''
).render( template.Context({}))
)
else:
if form2.is_valid():
post2 = Photo(user = request.user, alias = request.user.username, img = form2.cleaned_data['img'], title = "")
post2.save()
return HttpResponse(template.Template('''
<html><head><title>Uploaded</title></head> <body>
<h1>Uploaded</h1>
</body></html>
'''
).render( template.Context({}))
)
else:
form1 = DocumentForm()
form2 = PhotoForm()
return render_to_response('upload.html', {'form1': form1, 'form2':form2 }, context_instance=RequestContext(request))
我知道必须有更好的方法。任何帮助将不胜感激。感谢
答案 0 :(得分:0)
你真的需要两种不同的形式吗?看起来你可能只想要一个带有两个文件字段的表单。
if request.method == 'POST':
form = DocumentAndPhotoForm(request.POST, request.FILES)
if form.is_valid():
if form.cleaned_data.get('document'):
post1 = Document(user = request.user, document= form1.cleaned_data['document'], title = form1.cleaned_data['title'])
post1.save()
if form.cleaned_data.get('img'):
post2 = Photo(user = request.user, alias = request.user.username, img = form2.cleaned_data['img'], title = "")
post2.save()
return HttpResponse(template.Template('''
<html><head><title>Uploaded</title></head> <body>
<h1>Uploaded</h1>
</body></html>
'''
).render( template.Context({}))
)
return render_to_response('upload.html', {'form': form }, context_instance=RequestContext(request))
DocumentAndPhotoForm上的文件字段需要传入null=True
and blank=True
个参数。