我在其中一个页面上有一个Django表单,我试图使用Jquery-Ajax提交。
以下是我的代码:
我使用Jinja模板在页面上呈现表单。
<form action='' method='post' name='ContactForm' id='ContactForm'>
{% csrf_token %}
{% for field in form %}
<div class="input-group"> <span class="input-group-addon">@</span>
{{ field }}
</div>
{% endfor %}
<div class="input-group form-buttons"> <span class="input-group-btn">
<button class="btn btn-default" type='submit' value='Submit' name='submitf' id="submitf">SAY HELLO</button>
</span>
</div>
<div id='message_post'></div>
</form>
<script type="text/javascript" src="{% static 'personal/js/contact/contact-form.js' %}"></script>
与-form.js
$(function(){
$("#ContactForm").submit(function(){
$("#submitf").value='Please wait...';
alert("Control reached the script.");
$.post("/contact/add/", $("#ContactForm").serialize(),
function(data){
alert("Alert entered function.");
if(data.status == 'error'){
$("#message_post").html("<div class='errorMessage'>ERROR: " + data.msg + "!</div>");
document.ContactForm.submitf.value='Resend >>';
document.ContactForm.submitf.disabled=false;
} else {
$("#message_post").html("<div class='successMessage'>Hi! Glad to meet you. I'll definitely contact you shortly.</div>");
$("#submitf").value='Send >>';
}
}, "json");
return false;
});
});
urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^contact/add/$', views.add, name='add')
]
views.py
def add(request):
if request.method=='POST' and request.is_ajax():
form=ContactForm(request.POST)
if form.is_valid():
try:
form.save()
except Exception as e:
print ('%s' % str(e))
msg = 'That\'s embarrassing. Will you please Say Hello again?'
status = "Error"
else:
msg = 'Connected'
status = "Success"
print('status %s' % status)
request.write({'message':msg, 'status':status})
但每次点击提交按钮时都会出现以下错误:
POST /contact/add/ HTTP/1.1" 404 2043
我打算做的是当点击按钮时,表格中的数据应插入数据库。
提到以下链接和SO问题,但无法解决问题:
How to POST a django form with AJAX & jQuery
submitting a django form using javascript
目前处于Python和Django的学习阶段。非常感谢任何帮助。
答案 0 :(得分:1)
你能提供视图来检查吗?
尽管如此,请查看有关使用CSRF和ajax:https://docs.djangoproject.com/en/1.10/ref/csrf/
的文档您可能需要先添加一些AJAX设置。我正在为您提供一个可以帮助您的小小的要点:https://gist.github.com/silviomoreto/485b6a294b40f06011946d8be09c6e1f