I'm trying to tweak the existing XMLRenderer to create a custom one -
class CustomRenderer(renderers.BaseRenderer):
"""
Renderer which serializes to CustomXML.
"""
media_type = 'application/xml'
format = 'xml'
charset = 'utf-8'
def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Renders *obj* into serialized XML.
"""
if data is None:
return ''
stream = StringIO()
xml = SimplerXMLGenerator(stream, self.charset)
xml.startDocument()
xml.startElement("job id='string1'", {})
self._to_xml(xml, data)
xml.endElement("job")
xml.endDocument()
return stream.getvalue()
def _to_xml(self, xml, data):
if isinstance(data, (list, tuple)):
for item in data:
xml.startElement("string2", {})
self._to_xml(xml, item)
xml.endElement("string2")
elif isinstance(data, dict):
for key, value in six.iteritems(data):
xml.startElement(key, {})
self._to_xml(xml, value)
xml.endElement(key)
elif data is None:
# Don't output any value
pass
else:
xml.characters(smart_text(data))
For string1 I want it to get the value from the view that's calling it. string1 = the primary key from the GET in the API.
ie. if I'm calling http://localhost/API/2345 then string1 = 2345
For string2 I want it to return the model name similar to what they are doing in the following post -
Adding root element to json response (django-rest-framework)
Which is customizing the values returned by the Renderer so that the root value of the JSON/XML can be set as the model name.
I've tried tweaking the CustomRenderer to contain the lines but then when running my view it complains that "object() takes no parameters" on my views.py -
if request.method == 'GET':
DEV = Trgjob.objects.using('database1').filter(job_id=pk).order_by('job_order')
serializer = CustomSerializer(DEV, many=True)
return CustomRenderer(serializer.data)