Django CBV throwing an AJAX error with code 405 - Method Not Allowed

Help needed with POST and DELETE requests using Ajax! I have set up the methods in my class but something seems to be going wrong.

Any assistance would be much appreciated 😃

urls.py:

 path('<section>/add_wish/<slug>/', views.AddToWishlistView.as_view(), name='add_to_cart'),

My view :

class AddToWishlistView(LoginRequiredMixin, View):
    model = Wishlist
    http_method_names = ['POST']

    def POST(self, request, *args, **kwargs):
      wished_product = get_object_or_404(Product, slug=self.kwargs['slug'])
      new_item = self.model.objects.get(customer = self.request.user)
      new_item.product.add(wished_product)
      return HttpResponse(status=201)

And here's the Ajax code :

    $('.buy').click(function(e){
        e.preventDefault();

        let _this = $(this);
        var slug = _this.children().data('id');
        var section_slug = _this.data('section');

        $.ajax({
            type : 'POST',
            url :  '../'+section_slug + '/add_wish/' + slug + '/',
            success: function(data){
                if(data.success = true){
                    _this.addClass('clicked');
                }

            },
            async : false,
            error : function(data){
                console.log("ERROR");
                console.log(data);
                alert('LOOSERR');
            }
        })
    });

Answer â„–1

Make sure the method name is all in lowercase letters:

def post(self, request, *args, **kwargs):

Each request that reaches the view passes through the dispatch method, which is responsible for calling the appropriate method. You can learn more about how it operates here:

https://docs.djangoproject.com/en/3.0/ref/class-based-views/base/#django.views.generic.base.View.dispatch

and you can find the source code here:

https://github.com/django/django/blob/291539a85c8461456ab728fe6820a86de54294b6/django/views/generic/base.py#L93-L101

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The number input component that is meant to be reusable is experiencing functionality issues within the NUXT framework

I have a reusable input component that is being used in various places. Everything works well with the number input, but the issue arises when I completely clear the input. This action triggers a warning message in the console: [Vue warn]: Invalid prop: t ...

What is the best way to retrieve an object from the previous view (Class-Based View) in Django

Is there a simple way to retrieve the object value in CreateView from a previous DetailView without any issues? In the following code, how can I substitute '???'(inside CreateView) with an album object where album.pk == id as per the 'item- ...

Unleashing the power of the open form reveals a newly resized window

<script type="text/javascript"> function openSmallWindow() { .. // Specify URL, window size and attributes window.open('http://isivmwebtest.isolutionsinc.com/ComparativePricing/Content/PriceLookup.aspx','windowNew',&ap ...

Where should data processing be conducted: in the service or controller layer?

Here's a question regarding the best practices for organizing code. I'm fetching data from an API using $resource and I need to manipulate it before displaying it on the view. My dilemma is at which stage should I process the data? My current b ...

Is there a way to store the JWT response header retrieved with fetch?

I am currently utilizing React and employing fetch to send a request to the server: fetch("http://localhost:8001/api/login", { method: 'post', headers: { "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" }, ...

Is there a way to efficiently create an ng-repeat for multiple divs?

I am looking to iterate through a collection of divs, as mentioned below. Each object in the list will have content-data and a link to an image. The code provided shows individual entries for each list item, but I would like to retrieve it from the angular ...

Working with Foreign Object Names in Django Models: Implementing the __str__ Method

Currently, I am working with the Product and ProductImage models in Django. Each Product can have multiple associated ProductImage models. My goal is to have the product images display the name of the product they are linked to on the Django admin page. c ...

Issues with Django JQuery functionality are preventing proper operation

I am currently testing the functionality of JQuery in my Django project. I am encountering an issue where the event for an item is not working as expected. By reviewing my code below, the problem seems to arise when I reference the item "#text". (1) test. ...

Issues with Ajax causing problems with updating information in <h:selectOneMenu>

How can I update a selectOneMenu based on the selection of another selectOneMenu? I need the user menu to be dynamically updated when a group is selected. Although I can see that the data for the user menu is being updated, it's not rendering as exp ...

Attempting to showcase information on the Angular frontend

When attempting to retrieve the Street name, I am seeing [object Object]. What is the optimal approach for displaying JSON data on the client side? I managed to display a street name but struggled with other components. How can I access the other elements ...

merge two structures to create a unified entity

I have been searching in vain, can you please advise me on how to combine these two simple forms into one? I want it to be like a box with a select option and a button. The challenge for me is merging the two different actions, ".asp", into one script fo ...

How can I prevent the text from overlapping the lines in a d3 forced graph?

I am currently working with an SVG that contains text positioned in the center of a large circle, connected to two smaller circles by a line. The formula I am using to obtain the line coordinates is as follows: x1={Math.max(radius, Math.min(heigh ...

What is the best way to add a button click event listener that persists through DOM changes, such as in a single-page application?

I have developed a ViolentMonkey userscript that adds an event listener to a button with the ID #mark-watched. When this button is clicked, it automatically triggers a click on the button with the ID #next-video. This functionality is necessary because the ...

Executing a JavaScript function upon page load without the need for an onclick event

I have a footer.php file that contains JavaScript code and functions which I use on all of my pages. While I usually call the function MyFunc() using onclick event when clicking buttons, there are some pages where I need to call it without any user interac ...

Having trouble implementing server-side rendering with Styled-Components in Next JS

I attempted to resolve my issue by reviewing the code and debugging, but unfortunately, I couldn't identify the root cause. Therefore, I have posted a question and included _document.js, _app.js, and babel contents for reference. Additionally, I disa ...

When utilizing useMachine in TypeScript, an error is thrown regarding incompatible types

While attempting to build my first example for a xstate finite machine by following the example on github.com/carloslfu/use-machine, I encountered a TypeScript error that halted my progress: Argument of type '{ actions: { sideEffect: () => void; } ...

Uploading Files with Ajax - Script Corrupts Files during Upload

My Ajax-Fileupload Script is causing some issues for me. Whenever I upload files, they seem to become corrupt. Opening the file in Notepad++, I can see strange lines such as: -----------------------------22998260013704 Content-Disposition: form-data; name ...

"Executing a jQuery each function without pausing for the completion of an AJAX

When using the .each method in jQuery, it does not wait for the success of an Ajax call. $("img[name='statusIcon']").each(function () { var statusIcon = $(this); statusIcon.attr('src', 'images/spinner.gif'); //loading ...

Wicket: Efficiently loading DropDownChoice with lazy loading

A DropDownChoice list in my web application is taking an unusually long time to load due to complex operations with LDAP and SQL connections. As a result, the entire page is experiencing extended loading times, which is unacceptable. My goal is to use Wic ...

Is it possible for me to create a lineString connecting two points in OpenLayers3?

I need to create a lineString connecting my two given points, such as [-110000, 4600000] and [0, 0]. ...