简体   繁体   中英

Django: Uploading an XML file from HTML page

I am using Django framework and python scripts for validating XML files.

I usually parse the XML file, which is already present in the defined location, using the below code.

import xml.etree.ElementTree as ET
tree = ET.parse('config.xml')

However, now I want to add the file dynamically from the front end browse file option and place it in the above ET.parse('file.xml') location. What is the best way to achieve this?

<form action="/handle_xml_upload/" enctype="multipart/form-data" method="post">
    {% csrf_token %}
    <input type="file" name="xmlfile">

    <input type="submit" value="upload xml file">
</form>

and in views.py

def handle_xml_upload(request):
    xmlfile = request.FILES['xmlfile']
    tree = ET.parse(xmlfile)
    # ...

of course, you need adjust your urls.py as well ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM