'How do I put ajax on django class based update view

I have two submit buttons in my web-page. One of them is for submitting the form. The other one uses ajax to send the text inside a text-box to the server, processes it and returns back the result (in my case summary of the text) into another text-box.

This is the view I used, for creating post, it not only handles the page submission but also handles the ajax calls too:

class CreatePost(LoginRequiredMixin, View):
    def get(self, request, *args, **kwargs):
        if request.is_ajax():
            data = {
                'summary': summary
            }
            return JsonResponse(data)
        form = PostForm()
        context = {
            'form': form,
        }
        return render(request, 'posts/create_post.html', context)

    def post(self, request, *args, **kwargs):
        if 'news_submit_form' in request.POST:
            form = PostForm(request.POST, request.FILES)
    
            if form.is_valid():
                new_post = form.save(commit=False)
                new_post.publisher = request.user
                new_post.save()
                form = PostForm() # Clearing the form after submission

        if 'unsummarized_news' in request.POST:
            global summary
            unsummarized_news = request.POST['unsummarized_news']
            summary = get_summary(unsummarized_news)

        return redirect('home')

It works fine when creating a new post. But, my problem is that: I am unable to implement a view that is used to edit the already submitted post. Till now, I've been using this kind of view for handling post edits:

class PostEdit(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    fields = ['title','body','category', 'image']
    template_name = 'posts/post_edit.html'

    def get_success_url(self):
        pk = self.kwargs['pk']
        return reverse_lazy('post-detail', kwargs={'pk': pk})

    def test_func(self):
        post = self.get_object()
        return self.request.user == post.publisher

But this view is not aware of the ajax call being made in the page. And as soon as I press the button that is supposed to make the ajax call, the page refreshes and clears all the form data.

How do I handle ajax calls in a post edit view as shown above?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source