Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

784
Views
How do I return JSON response in Class based views, instead of HTTP response

I have a class based view. I am using Ajax on a bootstrap modal. To avoid page refresh, I want to return JSON response instead of HTTP response with this class based view- but I have only seen how to return JSON response for function based views.

views.py:

from django.contrib.auth.mixins import LoginRequiredMixin

class TaskCreateView(LoginRequiredMixin, CreateView):
    template_name = 'create.html'
    form_class = TaskForm
    success_url = reverse_lazy('task_list')

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs.update(user=self.request.user)
        return kwargs
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Try this: works for me. actually you have to override the post method if you are stick with Class-based Views.

import json

class TaskCreateView(LoginRequiredMixin, CreateView):
    form_class = TaskForm
    success_url = reverse_lazy('task_list')

...

def post(self, request, **kwargs):
     response_data = 'your data'

    return HttpResponse(json.dumps(response_data),content_type="application/json")
over 4 years ago · Santiago Trujillo Report

0

Try code below:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse

class TaskCreateView(LoginRequiredMixin, CreateView):
    template_name = 'create.html'
    form_class = TaskForm
    success_url = reverse_lazy('task_list')

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs.update(user=self.request.user)
        return kwargs

    def form_valid(self, form):
        return JsonResponse({'foo':'bar'})
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!