I have a view in django rest framework that allows me to generate a pdf, I want to get the data from models, I have this function in views.py
:
def generaPdf(request):
stu = models.ConfiguracionCv_Personalizado.objects.filter(id_user=4)
serializer = ConfiguracionCv_PersonalizadoSerializer(stu, many=True)
print(serializer.data)
json_data = JSONRenderer().render(serializer.data)
# PDF = generapdf.PDF
pdf = PDF()
pdf.alias_nb_pages()
pdf.add_page()
pdf.set_font('Times', '', 11)
for k, v in json_data.items():
pdf.cell(0, 10, f"{k}: {v}", 0, 1)
pdf = pdf.output(dest='S').encode('latin-1')
response = HttpResponse(pdf, content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"'
return(response)
In serializers.py
I have this:
class ConfiguracionCv_PersonalizadoSerializer(serializers.ModelSerializer):
class Meta:
model = ConfiguracionCv_Personalizado
fields = ('__all__')
I am trying to convert models.ConfiguracionCv_Personalizado.objects
to json to loop through it in the for and add the information to the pdf, but I am getting this error 'bytes' object has no attribute 'items'
. How can I convert models.ConfiguracionCv_Personalizado.objects
it to json and be able to go through it in the for. I hope you can help me. Thanks in advance.
the json cannot be traversed directly as you mention, to traverse it you must first convert it into a dictionary which python does understand, remember that although the json looks like the dictionary they are different objects so json cannot be traversed directly with a for loop use this line
json_data=json.loads(json_data)
right after the line. Jsonrenderer()....etc json_data with your current code, it's already a json object but it's not yet a dictionary object to go through with your for loop so this line converts json_data to a dictionary so you can iterate over it