Render JSON Django field

Asked

Viewed 34 times

-1

I am doing a project using Django 3.1.2, this project needs a log.

I created a template for logs:

class Log(models.Model):
    Usuario = models.CharField('Usuário que fez a ação', max_length=100)
    Perfil = models.SmallIntegerField('Quem está sofrendo a ação', choices=PERFIL_CHOICE)
    Acao = models.CharField('Tipo de Ação Realizada', max_length=2, choices=ACAO_CHOICE)
    Resultado = models.JSONField('Resultado', null=True, blank=True)
    Processando = models.BooleanField('Processando', default=True)
    TituloProcesso = models.CharField("Titulo do Processo", max_length=100, null=True, blank=True)
    DataAcao = models.DateTimeField('Data da Ação', auto_now_add=True)

The model log has the "Result" field which is of type Jsonfield, this field is working correctly.

The data that is saved in the field is dynamic, so the json keys and values will not always be the same, so it is necessary easier to display this field in the model.

I was looking for "Django-jsonfiel", it doesn’t work in Django 3.1

Does anyone know any way to display this already dynamically formatted field?

  • What do you call showing off? Something like print(json.dumps(SEU_JSON, indent=4, sort_keys=True)) helping?

  • Good afternoon, this would be a solution yes only that I tried to play in the template, putting this formatting in a variable so that in the template does not look the same in the terminal print, does not take the formatting.

  • Tries to pass the json.dumps(SEU_JSON, indent=4) to the template and show there with {{ VARIAVEL_JSON | linebreaks }}

  • Oops good morning, thanks a lot @Paulomarques worked, I was wondering if there are any tags for the identations and if you have any link with these tags so I can give a studied in them .

  • View the Django documentation here

1 answer

-1

Thanks Paul the line break with the "linebreaks" worked.

To with another doubt here that I can’t solve that and encode json pro utf-8.

in the terminal it displays normally encoded template no, I tried to encode before then I even managed to encode so that then it loses the formatting.

I tried that way but it won’t:

@login_required

def log_detail_view(request, log_id): objLog = Log.objects.get(pk=log_id) print(objLog.Result) data = str(objLog.Result). Ncode('utf-8') data = date.Decode('utf-8')

resultado = json.dumps(objLog.Resultado, indent=4)
print(resultado)
data = str(resultado).encode('utf-8')
data = data.decode('utf-8')
# print(data)
context = {
    'user': request.user,
    'objLog': objLog,
    'resultado': resultado,
}
return render(request, "relatorio/log_detail.html", context)

if anyone knows.

  • Another question another post. Do not make the chat room posts

Browser other questions tagged

You are not signed in. Login or sign up in order to post.