当我单击“提交”时,它是错误500(内部服务器错误)。我在“检查元素:网络”中看到此错误
这是我的代码:
HTML
const query = e.target.value // or whatever the source you get the query from
if(query) {
this.setState({query: [query]})
}
JS
<form id="new_user_form">
<input type="text" id="name" placeholder="Name" name="" value="">
<select class="" name="skill_type" id="type">
<option value="1">Developer</option>
<option value="2">Network</option>
<option value="3">System</option>
<option value="4">Database Analysis</option>
</select>
<input type="submit" name="" value="submit">
</form>
view.py
$(document).on('submit','#new_user_form',function(e){
e.preventDefault();
$.ajax({
type : 'POST',
url : 'skill/create',
data : {
name : $('#name').val(),
type : $('#type').val(),
},
sucess:function(){
}
});
});
这是图像错误:enter image description here
请帮助我TT
答案 0 :(得分:0)
您也需要在ajax中发布csrf_token:
$(document).on('submit','#new_user_form',function(e){
e.preventDefault();
$.ajax({
type : 'POST',
url : 'skill/create', // hardcoding urls? not a good idea, use {% url 'url_name' %}
data : {
name : $('#name').val(),
type : $('#type').val(),
csrfmiddlewaretoken: $('input[name="csrfmiddlewaretoken"]').val() // No traling comma
},
sucess:function(){}
});
});
现在修复您的模板:
<form id="new_user_form">
{% csrf_token %} // add csrf token
<input type="text" id="name" placeholder="Name" name="name" value=""> // add name
<select class="" name="skill_type" id="type">
<option value="1">Developer</option>
<option value="2">Network</option>
<option value="3">System</option>
<option value="4">Database Analysis</option>
</select>
<input type="submit" value="submit"> // submit doesn't require name attribute
</form>
使用html输入元素的名称来获取POST数据,因此在您看来:
def create_skill(request):
if request.method == 'POST':
name = request.POST['name']
type = request.POST['skill_type'] # name for select in your html is 'skill_type' so use that
skill = Skill(skill_name=name,skill_type=type)
skill.save()
return HttpResponse('') # Empty HttpResponse doesn't makes much sense, also for ajax I would recommend JsonResponse