python - Django: Uploading photo and word doc on same form not working correctly -
i have upload form allow user upload photo, word doc, or both. need logic long have photo or document selected uploading, form valid , upload work. works when have both photo , doc, appears randomly work when it's photo or document. here 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() , 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 better way. appreciated. thanks
do need have 2 different forms? seems may want 1 form 2 file fields.
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))
your file fields on documentandphotoform need have null=true
, blank=true
parameters passed in though.
Comments
Post a Comment