djangodjango-viewsdjango-jsonfield

Django convert CBV to json


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


Solution

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