django文件上传功能

今天需要一个文件上传功能,所以代码如下

def ci_test(request):
    try:
        if request.POST.has_key("send"):
            xml_string=""
            final_xml = ""
            file_obj = request.FILES.get('file', None)
            for keys in request.POST:
                if request.POST[keys]:
                    print keys,request.POST[keys]
                    xml_string = "<%s>%s</%s>n%s" % (keys,request.POST[keys],keys,xml_string)
            final_xml = "<root>n%s</root>" % xml_string
            dirname = os.path.dirname(os.path.abspath(__file__))
            parent = os.path.split(dirname)[0]
            if request.POST["source"] == "text" and file_obj:
                if file_obj.name.endswith(".txt"):
                    #print parent

                    filepath = "%s/core/emaillist.txt" % parent
                    #print filepath

                    open(filepath,'w').write(file_obj.read())  #注意这里

                else:
                    raise forms.ValidationError("上传文件类型错误!")
            path = "%s/core/config/%s.xml" % (parent,request.POST['txtDate'])
            open(path,'w').write(final_xml.encode('utf-8'))
        else:
            smtp = request.POST['smtp']
            username = request.POST['username']
            passwd = request.POST['passwd']
            title = request.POST['title']  #邮件标题

            content = request.POST['content']  #邮件内容

            attach = request.POST['useattach']  #是否是附件发送

            ctype = request.POST['c_type']  #邮件格式

            testsend = request.POST['testsend']#测试邮箱

            subtem = u"%s:  %s" % (u"测试",title)
            conn = creat_conn(smtp, username, passwd)
            tem = testsend.split(';')
            if ctype.upper() == "HTML":  
                final_body = creat_htmlbody(content)
                    #测试发送,不用记录日志直接传列表

                final_testmail(subtem,final_body,username,tem,conn,attach)
                print "test send  to %s sucess!" % tem
            else:
                final_testmail(subtem,content,username,tem,conn,"test")
                print "test send  to %s sucess!" % tem
        return render(request,'test.html',{"msg":"请求已经提交,关闭本页面即可"})
    except forms.ValidationError:
        print "in my error"
        return render(request,'test.html',{{"msg":"文件类型错误,请重新操作!"}})
    except Exception:
        return render(request,'test.html',{{"msg":"发生错误,请重新操作!"}})

此处需要注意模版文件中form的写法:

<form action="ci_test" method="post" onsubmit="return validate_form(this);" enctype="multipart/form-data">
<input type="file" name="file"/>
</form>

不过此处有个奇怪的问题,根据流程来看,如果上传的不是.txt文件则引发异常,也确实输出了"in my error"这句话,不过随后就引发了下面的异常,不知道render为什么错误。

TypeError at /mailinfo/ci_test
unhashable type: 'dict'
Request Method:         POST
Request URL:    http://127.0.0.1:8000/mailinfo/ci_test
Django Version:         1.5.3
Exception Type:         TypeError
Exception Value:        
unhashable type: 'dict'
Exception Location:     /home/xingsongyan/workspace/send/mailinfo/views.py in ci_test, line 66
Python Executable:      /usr/bin/python2.7
Python Version:         2.7.5
Python Path:    
['/home/xingsongyan/workspace/send',
 '/usr/lib/python2.7/site-packages/pip-1.4.1-py2.7.egg',
 '/home/xingsongyan/workspace/send',
 '/usr/share/eclipse/dropins/pydev/eclipse/plugins/org.python.pydev_2.8.2.2013090511/pysrc',
 '/usr/lib64/python27.zip',
 '/usr/lib64/python2.7',
 '/usr/lib64/python2.7/plat-linux2',
 '/usr/lib64/python2.7/lib-tk',
 '/usr/lib64/python2.7/lib-old',
 '/usr/lib64/python2.7/lib-dynload',
 '/usr/lib64/python2.7/site-packages',
 '/usr/lib64/python2.7/site-packages/gtk-2.0',
 '/usr/lib64/python2.7/site-packages/wx-2.8-gtk2-unicode',
 '/usr/lib/python2.7/site-packages',
 '/usr/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg-info',
 '/usr/lib64/python2.7/site-packages/PIL']
Server time:    Wed, 4 Dec 2013 16:05:25 +0800