Home > Software design >  Django convert CBV to json
Django convert CBV to json

Time:09-04

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

CodePudding user response:

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}}.

  • Related