Search code examples
pythondjangodjango-templatesdjango-database

parse template tag to XML in Django


I am trying to print get some value from database and print into xml dynamically.

This is my model:

class Somemodel(models.Model):
    Party_Id = models.CharField(max_length=500)
    Label = models.CharField(max_length=500)
    Party_Id = models.CharField(max_length=500)
    Name = models.CharField(max_length=500)

This is my view function

def xmlcontent(request):
  obj = Somemodel.objects.get(pk=1)
  obj.Party_Id = obj.pk
  pprint.pprint(obj.DDEX_Party_Id)
  return render(request, "content.xml", {"DDID": "obj"},
content_type =   "application/xhtml+xml")

My content.xml looks like this

<?xml version="1.0" encoding="UTF-8"?><br/>
<</MessageHeader>MessageHeader><br/>
    {% for i in DDID %}<br/>
        {{ i.pk }}<br/>
    {% endfor %} <br/>
<</MessageHeader>/MessageHeader><br/>

Its suppose to print Party_id but not printing.. Am i miss something ?


Solution

  • A few problems:

    1. You are sending the string "obj" instead of the object obj in your context dictionary.
    2. In your xml template, you have a loop, but the context variable DDID is going to be a single object, not a collection or queryset, because you are using .get.
    3. You have extra < in your XML, and XML does not include <br /> tags. The resulting file will be invalid.

    To save yourself some trouble, just use the built-in serializers. The first example shows you how to export XML:

    from django.core import serializers
    
    def some_method(request):
        XMLSerializer = serializers.get_serializer("xml")
        xml_serializer = XMLSerializer()
        xml_serializer.serialize(SomeModel.objects.filter(pk=1).values('id'), stream=request)