Django convert CBV to json

52 Views Asked by At

I have this CBV

class Ansicht(AdminStaffRequiredMixin, LoginRequiredMixin, DetailView):
    model = User
    template_name = 'SCHUK/Ansicht.html'
    context_object_name = 'Ansicht'
 


Im using _set to display all users data to staff. But I need to use the data for calculations, how can I convert this to json

1

There are 1 best solutions below

0
nigel239 On BEST ANSWER

Use model_to_dict.

Then you can define a method on your model:

from django.forms.models import model_to_dict
class MyModel...
    def get_json(self):
        return json.dumps(model_to_dict(self))
    

In your template, you can just call {{instance.get_json}}.