Liondancer
Liondancer

Reputation: 16469

ajax request to view in Django producing 404

For my ajax request I am getting a 404

[06/Feb/2015 06:46:27] "POST /contact/ HTTP/1.1" 404 2149

I am new to AJAX but I think what my logic is doing sending a POST request to the /contact/ url. This would send the request to the contact function in my views and print out some text (For testing purposes for now). I am not sure why I am getting a 404. I am quite new to Django and web dev in general.

js:

    function create_post() {
        console.log("create post is working");
        var firstName = document.getElementById("firstname");
        var lastName = document.getElementById("lastname");
        var email = document.getElementById("email");
        var phoneNumber = document.getElementById("phonenumber");
        var message = document.getElementById("message");
        var contactInfo = {
            "first_name": firstName.value,
            "last_name": lastName.value,
            "email": email.value,
            "phone_number": phoneNumber.value,
            "message": message.value
        };

        $.ajax({
            url: "/contact/",
            type: "POST",
            data: contactInfo,
            success: console.log(contactInfo),
            error: console.log("ajax fail")

        });
    };


//    Contact form submit
    var contactForm = document.getElementById("contact-form");
    $(contactForm).on('submit', function(event) {
        event.preventDefault();
        console.log("form submitted");
        create_post();
    });

I have a guess it might be my urls?

home/urls.py:

urlpatterns = patterns('',
    url(r'^$', load_home_content),
    url(r'^contact/$', contact, name="contact"),
)

urls.py:

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', include('home.urls'), name='home'),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

home/views.py:

def contact(request):
    if request == "POST":
        print request.POST
        form = ContactForm(request.POST)
        print form.first_name, form.last_name, form.email, form.phone_number
        if form.is_valid():
            print "form valid"
        else:
            print "form invalid"
    return render(request, 'home/home.html', {'form': ContactForm})

Developer tools output:

enter image description here

enter image description here

Upvotes: 1

Views: 1634

Answers (1)

catavaran
catavaran

Reputation: 45575

Remove the $ sign from the inclusion url:

url(r'^', include('home.urls'), name='home'),

Upvotes: 3

Related Questions