0

I'm trying to submit a django form via ajax, but I get this error message: Btw my urlpatterns should be fine, they work properly when I simply render the site.

jquery-3.5.1.js:10099 POST http://127.0.0.1:8000/%7B%%20url%20%22landing-home%22%20%%7D 404 (Not Found)

Here's my url file:

from django.urls import path
from Landing import views

urlpatterns = [
  path('', views.home, name='landing-home'),
]

My ajax call:

$(document).ready(function(){
console.log("Ready!");

const form = document.getElementById("form");
form.addEventListener("submit", submitHandler);

function submitHandler(e){
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url: '{% url "landing-home" %}',
        data: $('#form').serialize(),
        dataType: 'json',
        
        success: function(data){
            if(data.msg == 'Success'){
                alert("Form is submitted!");
            }
        }

    })
}


})

2 Answers 2

2

It's not clear from your code, but I'm guessing that your ajax function is stored in a dedicated javascript file, rather than in the template that is calling it, yes?

If so, the issue is clear: inside the ajax function, you are using a django template tag to assign the url: {% url "landing-home" %}. A template tag is evaluated by django when the template is loaded. If the ajax function doesn't exist in a template file, that tag cannot and will not be loaded at all. Your javascript file, assuming you have one and that is where your ajax call code exists, has no ability to evaluate django template tags.

The 'easy' solution is to simply move the ajax function to the bottom of the template that calls it, and put it inside a < script > tag. Make sure your javascript / jQuery is properly loaded in your base template and extended into the template that will be using it. With this done, the template tag will evaluate to the proper URL when the template is loaded, and your specific error is resolved.

If you desire to keep the ajax function inside its own dedicated file, you'll need to create a workaround for getting the necessary URL without using a django template tag. I don't have an immediate answer for this, but I believe I've seen it discussed in various threads here on Stack Overflow, and elsewhere, so you should do some research on that.

Sign up to request clarification or add additional context in comments.

Comments

0

A very simple workaround is to write the url in the ajax request like this:

url : 'yourURL'

with or without the / depending on your config.

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.