gpt4 book ai didi

python - ajax 请求在 Django 中查看产生 404

转载 作者:行者123 更新时间:2023-11-30 23:15:13 25 4
gpt4 key购买 nike

对于我的 ajax 请求,我收到 404

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

我是 AJAX 新手,但我认为我的逻辑是向 /contact/ url 发送 POST 请求。这会将请求发送到我的 View 中的 contact 函数并打印出一些文本(目前用于测试目的)。我不知道为什么会收到 404 错误。总的来说,我对 Django 和 Web 开发还很陌生。

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();
});

我猜这可能是我的网址?

home/urls.py:

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

url.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})

开发人员工具输出:

enter image description here

enter image description here

最佳答案

从包含网址中删除 $ 符号:

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

关于python - ajax 请求在 Django 中查看产生 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28360266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com