I have an upload form that will allow a user to upload a photo, a word doc, or both. I need help with the logic so that as long they have a photo OR a document selected for uploading, the form is valid and the upload will work. It always works when I have BOTH a photo and doc, but appears to randomly work when it’s just a photo or document. Here is my current code:
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))
I know there has to be a better way. Any help would be greatly appreciated. Thanks
Do you really need to have two different forms? It seems like you may just want one form with two file fields.
Your file fields on the DocumentAndPhotoForm will need to have the
null=Trueandblank=Trueparameters passed in though.