Can not post form data in a specific xml format using Django

时间:2017-06-15 10:04:03

标签: python xml django

I need one help. I need to save all data into a specific xml format using Django. I am explaining my code below.

bmr.html:

<form method="post" action=" ">
    {% csrf_token %}
    <label>location name: </label>
    <input name="lname">
    <br>
    <label>Room name: </label>
    <input name="rname">
    <br>
    <label>No of Seats: </label>
    <input type="number" name="seat">
    <br>
    <label>Projector Screen</label>
    <select name="projector">
      <option value="Yes">Yes</option>
      <option value="No">No</option>
    </select>
    <br>
    <label>Video conference</label>
    <select name="video">
      <option value="Yes">Yes</option>
      <option value="No">No</option>
    </select>
    <br>
    <input type="submit" value="Submit">
</form>

views.py:

from __future__ import unicode_literals
from django.shortcuts import render, redirect
from django.contrib.auth import get_user_model, login, logout
from django.contrib.auth.decorators import login_required
from django.views import View
from django.contrib.auth.forms import (UserCreationForm, AuthenticationForm)
import xml.etree.cElementTree as ET
def bmr(request):
    root = ET.Element("roomlist")
    ET.SubElement(roomlist, "location name", name="blah").text = "some value1"
    doc = ET.SubElement(root, "location")
    return render(request,'booking/bmr.html',{})

Here I need when user will click on submit button the post data will save into following xml format. I am explaining my format below.

<roomlist>
  <location name="Bangalore">
    <room id="1uy92j908u092">
      <roomname> Aquarius </roomname>
      <noseats> 10 </noseats>
      <projectorscreen>yes</projectorscreen>
      <videoconf>yes</videoconf>
    </room>
  </location>
  <location name="Sydney">
    <room id="324det56yuygttrgr">
      <roomname> Capricorn </roomname>
      <noseats> 5 </noseats>
      <projectorscreen>no</projectorscreen>
      <videoconf>yes</videoconf>
    </room>
  </location>
</roomlist>

After save into xml file it should also display in that below part of the form in table structure. Please help me.

1 个答案:

答案 0 :(得分:0)

in your template

<form method="post" action="{% url 'for_the_view' %}">

in your views

def bmr(request):
    location_name = request.POST.get('lname') //same for other fields
    root = ET.Element("roomlist")
    ET.SubElement(roomlist, "location name", name="blah").text = location_name // sane for other fields
    tree = ET.ElementTree(root)
    tree.write("filename.xml")
    return render(request,'booking/bmr.html',{})