Ajax call to view giving me a 404 error but it's the right URL in Django

Related searches

I am trying to send a post request via Ajax and Django but I keep getting a 404 error even though the POST url is the correct URL I want to use.

Here is my form minimised I'm trying to send and value through a button.

<form class='my-ajax-form' method='POST'>{% csrf_token %}

  <div class="btn-group" role="group" aria-label="Basic example">
  <button type="text" class="btn btn-danger hard" name="hard" value="HARD">HARD </button>
  </div>

</form>

Here is my Ajax form:

My CSRF code as I was getting an error before but not now.

<script>
             $(document).ready(function() {

                function getCookie(name) {
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        // Does this cookie string begin with the name we want?
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;

            }
            var csrftoken = getCookie('csrftoken');
            var $endpoint = $(location).attr('href')

            function csrfSafeMethod(method) {
                // these HTTP methods do not require CSRF protection
                return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
            }
            $.ajaxSetup({
                beforeSend: function(xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                }
            });

My Ajax call:

            $('.hard').click(function(e) {
                event.preventDefault();
                var $hard = $(".hard").text();
                console.log($hard) 

                $.ajax({                        
                    method:'POST',
                    url: $endpoint,
                    data: $hard,
                })                   

            })   
            });

My urls file

urlpatterns =[

path('profile/<int:pk>/',  login_required(UserUpdateView.as_view()), name='profile'),

]

And my result is → POST http://127.0.0.1:8000/profile/11/ 404 (Not Found)

The url where the call is created is http://127.0.0.1:8000/profile/11/

I just want to send the request to the View, there is not error on the screen only in the console.

Thanks for any help

View was requested but the POST request is not reaching the View. Here is is

class UserUpdateView(UpdateView):

model = user_content
template_name = 'users/profile.html'
model_words = single_words_cards



def get(self, request, *args, **kwargs):
    model = user_content
    model_words = single_words_cards
    template_name = 'users/profile.html'
    user_id_fk = request.user.id



    # Hide the sentance
    if request.method == "POST":

        if request.GET.get('hard') == 'hard':
            print('hard was found')
        else:
            print('nothing')

        hide = model.objects.filter(show_sentance = True).values('sentance_eng').filter(id=query)
        model.objects.filter(id=retire).update(show_sentance='False')
        print(retire )


    #Querysets 
    user_sentances = model.objects.filter(show_sentance = True).values('sentance_eng', 'sentance_esp', 'id', 'username_id', 'show_sentance').filter(username_id = user_id_fk) 
    zip_flash_sentances = model.objects.filter(show_sentance=True).order_by("?").filter(username_id = user_id_fk).values_list('sentance_eng', 'sentance_esp', 'id').first()
    number_sentances_today = model.objects.filter(show_sentance=True).values_list('sentance_eng').filter(username_id = user_id_fk).count()

    word_cards_esp = list(model_words.objects.filter(show_word=True).values_list('word_esp').filter(username_id = user_id_fk))
    word_cards_eng = list(model_words.objects.filter(show_word=True).values_list('word_eng').filter(username_id = user_id_fk))
    number_of_cards = len(model_words.objects.filter(show_word=True).values_list('word_esp').filter(username_id = user_id_fk))

    value = random.randint(0,number_of_cards)-1


    words_esp = word_cards_esp[value] 
    words_eng = word_cards_eng[value]




    return render(request, template_name, {'sentances_list': user_sentances,
                                           'zip_flash_sentances':zip_flash_sentances,
                                           'words_esp':words_esp,
                                           'words_eng':words_eng,
                                           'number_sentances_today':number_sentances_today, 
                                           'number_of_cards':number_of_cards, 
                                           'user_id_fk': user_id_fk,

                                           })

For post request in UpdateView, you need to create post method.

Something like this will work:

class UserUpdateView(UpdateView):

    model = user_content
    template_name = 'users/profile.html'
    model_words = single_words_cards


    # Get Method 
    def get(self, request, *args, **kwargs):
        model = user_content
        model_words = single_words_cards
        template_name = 'users/profile.html'
        user_id_fk = request.user.id

        #Querysets 
        user_sentances = model.objects.filter(show_sentance = True).values('sentance_eng', 'sentance_esp', 'id', 'username_id', 'show_sentance').filter(username_id = user_id_fk) 
        zip_flash_sentances = model.objects.filter(show_sentance=True).order_by("?").filter(username_id = user_id_fk).values_list('sentance_eng', 'sentance_esp', 'id').first()
        number_sentances_today = model.objects.filter(show_sentance=True).values_list('sentance_eng').filter(username_id = user_id_fk).count()

        word_cards_esp = list(model_words.objects.filter(show_word=True).values_list('word_esp').filter(username_id = user_id_fk))
        word_cards_eng = list(model_words.objects.filter(show_word=True).values_list('word_eng').filter(username_id = user_id_fk))
        number_of_cards = len(model_words.objects.filter(show_word=True).values_list('word_esp').filter(username_id = user_id_fk))

        value = random.randint(0,number_of_cards)-1


        words_esp = word_cards_esp[value] 
        words_eng = word_cards_eng[value]




        return render(request, template_name, {'sentances_list': user_sentances,
                                            'zip_flash_sentances':zip_flash_sentances,
                                            'words_esp':words_esp,
                                            'words_eng':words_eng,
                                            'number_sentances_today':number_sentances_today, 
                                            'number_of_cards':number_of_cards, 
                                            'user_id_fk': user_id_fk,

                                            })

    # Post Method 
    def post(self, request, *args, **kwargs):
        model = user_content
        model_words = single_words_cards
        template_name = 'users/profile.html'
        user_id_fk = request.user.id


        if request.GET.get('hard') == 'hard':
            print('hard was found')
        else:
            print('nothing')

        hide = model.objects.filter(show_sentance = True).values('sentance_eng').filter(id=query)
            model.objects.filter(id=retire).update(show_sentance='False')
        print(retire )
        # Process your request

Ajax method give me back allows an 404 error, I'm not sure if this is a pw issue, anyway I would like to check. I have ajax call for a contact form that give me back every time an 404 error. Selecting an option in the first select box does an ajax call to my controller that populatest the second select box. This works just fine on my winxp dev machine but returns a 404 on the call to the controller when running on the server. Code for that call: <% Html.EnableClientValidation (); %>

The problem is in the view. In class based view you need to defined each method individually. In your code is only the GET method. You need another function for the POST method.

Actionmethods throw 404 on POST/AJAX calls after deploying the , Actionmethods throw 404 on POST/AJAX calls after deploying the application on IIS. finally included this in web.config, but still it gives 404 not found error. This pattern allows us to pass a variable (URL) to the function. All you have to do is get the URL values from the Action to the View or Partial View. It gives me an "404 Not Found Error" and the response on Firebug says "No input file specified". Everything else on ajax works fine in my website, this is the only one giving me trouble. I'm thinking it's JSON problem because the other ajax requests I'm using are HTML responses.

I assume your urls.py is not in the Django project directory but rather in one of your app directory thereby including the app_name before the url_patterns. Can you please share your directory structure?

Ajax call through admin-ajax.php returns 404 error, success and error are functions, not properties of AJAX function. Working code: $ (".tabs .btn").click(function(e) { e.preventDefault(); $.ajax({� I think you're right about giving direct access to index.php I also read the comment append with the changes into form.inc and I realize it's not a security fix. Thanks

The problem is in your urls pattern

urls.py

from django.conf.urls import url

urlpatterns = [
    url(r'^profile/(?P<your_variable_name>\d+)/$', login_required(UserUpdateView.as_view()), name='profile'),
    ]

Note: You may get arguments error in your view, so you may use

def your_view(request, your_argument):

Sitecore api call giving 404 on ajax post call on CD server, ajax call. The controller inherits ServicesApiController . The ajax Get method is works fine on CD server. But the post method is give 404 error. 404 errors received when opening links via Microsoft Office applications generate a The Internet site reports that the item you requested could not be found (HTTP/1.0 404) message inside the MS Office program.

jQuery Ajax request with error 404 (not found) but it works, jQuery Ajax request with error 404 (not found) but it works - javascript. AJAX request to the server, but the browser's console tells me that the page is not way I am currently calling the URL in my view is wrong since I get an 404 error on I checked almost all questions in stackoverflow, but the given solutions didn't help. everything looks fine, but did not get value from controller to ajax call, give as undefined. I just tried returning number from controller to ajax call, still gets data value is undefined. please try to solve it,

It might be the case that the page in question has been moved to a new URL, and in this scenario you will be doing the website operator a big favor. They can then carry out a 404 error fix by introducing a domain redirect, which will automatically direct users from the old web page to the current one.

Our website has received numerous WebResource 404 errors after upgrading to .NET Framework 4.0 along with all Windows Updates for that framework. We did not have this issue with Telerik and .NET Framework 2.0. We have tried the suggestions given by the Telerik web site as to web.config changes to resolve 404 errors. This did NOT work.

Comments
  • Show the view, please. What is UserUpdateView?
  • The reason why I've asked is it first project, becouse many nowadays tutorial makers don't explain why you should do like this . And after watching this tutorials you don't know neither alternative ways nor advenced approach. My sugestion isto find good communtiy (May be your local pyCon).
  • maybe you are getting this issue because of url conflicting with each other, add your other urls and error in the console. one more doubt, are you able to make a GET request to 127.0.0.1:8000/profile/11 url?
  • Could you try this in the Django shell (I'm on version 1.11) and see that this doesn't throw a 403: from django.urls import resolve; resolver_match = resolve('/profile/1/')
  • 404 because it can't find the post method. This is the correct answer.
  • then the status code should be 405 [Method not allowed], instead of 404.
  • All you did was change from 2.x url notation to 1.x. Functionally, your answer is identical
  • Identical to what?
  • identical to the url configuration the OP posted
  • There is difference between path and url. What are you talking about? Beside this answer is working, while code in question was not
  • There is a slight difference between path and url, but functionally nothing that would affect OP's situation. Your solution is great for 1.11.x, but OP's fine in 2.x