1

I have page where I render datatables to display the data with buttons like edit and delete per row,I have also one global button to create new entry. The create button opens a modal form which is standard bootstrap model. I am using this same form to create & update records.So if refresh my page & create one new entry it works but without refresh when click on the edit button then submit the modal form it gives me this error,

CSRF verification failed. Request aborted.

All this operations are performed using the AJAX request so I am not reloading the page after each request.How can I resolve this? Here is my server side code you want to take a look,

class CategoryView(AdminLoginRequiredMixin,View):
    
    def post(self, request):
        form = DownloadableCategoryForm(request.POST)

        if not form.is_valid():
            return JsonResponseBuilder.validation_error(form.errors)

        form.save()
       
        return JsonResponseBuilder.success('Category created succesfully...')

    # to update category
    def put(self, request):
        try:
            category = DownloadableCategory.objects.get(pk=request.POST.get('id'))
        except DownloadableCategory.DoesNotExist:
            return JsonResponseBuilder.error('Category not found!', HTTPStatus.NOT_FOUND.value)

        form = DownloadableCategoryForm(request.POST,instance=category)

        if not form.is_valid():
            return JsonResponseBuilder.validation_error(form.errors)

        form.save()
        
        return JsonResponseBuilder.success('Category updated succesfully...')

Here is my JS code which I am using to create/update records

$.ajax({
                    url: "{% url 'admin:create_downloadable_category' %}",
                    method: id.length == 0 ? "POST" : "PUT",
                    data: new FormData(form[0]),
                    processData: false,
                    contentType: false,
                    beforeSend: function () {
                        $('.pre-loader-screen').fadeIn(200);
                    },
                    
                    error: function (err) {
                        console.log(err);
                        error = JSON.parse(err.responseText)

                        swal(
                            {
                                title: "Error!",
                                text: error['message'] || 'Internal Server Error!',
                                type: "error",
                                showCancelButton: true,
                                closeOnConfirm: true,
                            })

                    },
                    success: function (response) {
                        categoryModal.modal('hide')
                        $('.pre-loader-screen').fadeOut(200);
                        reloadDatatable()
                        toastr.success(response.message);
                    }
                });

Edit: I came to know that update method is not working even if I refresh the page & try to update the records. It just giving me 403 error.

Ropali Munshi
  • 2,757
  • 4
  • 22
  • 45

1 Answers1

1

You should render the modal content from the server. When user clicks on the modal to create/update the object at that time you have to fire AJAX call for the updated modal content and update the modal content.

You should create a AJAX view which gives you a modal content.