5

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
1
  • 2
    Override the post(...) method of CBV Commented Jan 8, 2020 at 12:08

2 Answers 2

5

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'})
Sign up to request clarification or add additional context in comments.

Comments

1

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.