我希望你可以帮助我,我试图制作一个django帖子表格而无需使用ajax重新加载页面,但我在提交时收到错误500,你能帮我解决这个问题,这是我的代码:
models.py
class ProductoConcepto(models.Model):
producto = models.ForeignKey(Producto)
orden = models.ForeignKey(Cobro)
cantidad = models.FloatField()
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from cobro import views
urlpatterns = [
url(r'^cobro/agregar_concepto/$', views.addconcept_product, name='add_concepto'),
]
views.py
def addconcept_product(request):
if request.method == 'POST':
if form.is_valid():
producto = request.POST['producto']
orden = request.POST['orden']
cantidad = request.POST['cantidad']
ProductoConcepto.objects.create(producto=producto, orden=orden, cantidad=cantidad)
return HttpResponse('')
模板
<div class="modal inmodal fade" id="myModal1" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-m">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Cerrar</span>
</button>
<h3 class="modal-title">Agregar nuevo concepto</h3>
</div>
<div class="modal-body">
<p>Datos de concepto a agregar:</p>
<div class="doctorformstyle">
<form id='formulario-modal' method='post' enctype='multipart/form-data'>
{% csrf_token %}
<ul>{{form2.as_p}}</ul>
<!-- rendered form2 fields: <select id="id_producto" name="producto"><option value="1" selected="selected">object</option></select> -->
<!-- form2 fields: <select id="id_orden" name="orden">
<option value="1" selected="selected">object</option>
</select> -->
<!-- form2 fields: <input id="id_cantidad" name="cantidad" step="any" type="number"> -->
<div class="row align-center">
<input type='submit' name="save1" value='Guardar' class="btn btn-w-m btn-primary"/>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).on('submit', '#formulario-modal', function(e){
e.preventDefault();
$.ajax ({
type: 'POST',
url: '{% url 'add_concepto' %}',
data: {
producto: $('#id_producto').val(),
orden: $('#id_orden').val(),
cantidad: $('#id_cantidad').val(),
csrfmiddlewaretoken: '{{ csrf_token }}',
},
sucess:function(){
alert("OK");
}
})
});
</script>
这是错误:POST http://127.0.0.1:8000/cobro/agregar_concepto/ 500(内部服务器错误)
我认为在我的观点中可能缺少某些东西,买,我不知道,你能帮帮我吗?
编辑:添加了回溯
环境:
请求方法:GET请求URL: http://127.0.0.1:8000/cobro/agregar_concepto/
Django版本:1.9.7 Python版本:2.7.11已安装的应用程序: (&#39; django.contrib.admin&#39;,&#39; django.contrib.auth&#39;, &#39; django.contrib.contenttypes&#39;,&#39; django.contrib.sessions&#39;, &#39; django.contrib.messages&#39;,&#39; django.contrib.staticfiles&#39;,&#39; entrada&#39;, &#39; cobro&#39;,&#39; catalogo&#39;,&#39; selectize&#39;,&#39; smart_selects&#39;)已安装 中间件:(&#39; django.contrib.sessions.middleware.SessionMiddleware&#39;, &#39; django.middleware.common.CommonMiddleware&#39 ;, &#39; django.middleware.csrf.CsrfViewMiddleware&#39 ;, &#39; django.contrib.auth.middleware.AuthenticationMiddleware&#39 ;, &#39; django.contrib.auth.middleware.SessionAuthenticationMiddleware&#39 ;, &#39; django.contrib.messages.middleware.MessageMiddleware&#39 ;, &#39; django.middleware.clickjacking.XFrameOptionsMiddleware&#39)
回溯:
文件&#34; C:\ Python27 \ lib \ site-packages \ django \ core \ handlers \ base.py&#34;在 get_response 158.%(回调。模块,view_name))
异常类型:/ cobro / agregar_concepto / Exception的ValueError 值:视图cobro.views.addconcept_product没有返回 HttpResponse对象。它改为返回None。
答案 0 :(得分:0)
您查看的内容不完整: 正如异常所述:视图cobro.views.addconcept_product未返回正确的HttpResponse对象。
return HttpResponseRedirect('/thanks/')
答案 1 :(得分:0)
使用类似的内容更新您的return语句。
from django.http import JsonResponse
另外,当您使用ajax时,您还可以返回JsonResponse。
首先导入
JsonResponse({'success': 'Product created'})
然后返回您的回复
def addconcept_product(request):
if request.method == 'POST':
if form.is_valid():
....
return JsonResponse({'success': 'Product created'})
else:
return JsonResponse({'error': 'InValid Form.Product Creation Failed'})
else:
return JsonResponse({'error': 'Only POST method allowed'})
如果方法不是POST,并且您正在提交GET请求,那么会引发异常,因为您没有处理该条件。
处理无效表单的情况,如果方法不是POST。
$.ajax ({
method: 'POST',
url: '{% url 'add_concepto' %}',
....
});
还使用ajax方法属性而不是类型。
NULL
答案 2 :(得分:0)
您是否正在查看在新窗口中提供的例外情况?因为它正在展示 “请求方法:GET”,不应该通过你的ajax函数发生。
将您的观点修改为:
def addconcept_product(request):
if request.method == 'POST':
if form.is_valid():
producto = request.POST['producto']
orden = request.POST['orden']
cantidad = request.POST['cantidad']
ProductoConcepto.objects.create(producto=producto, orden=orden, cantidad=cantidad)
return HttpResponse('Product Created')
else:
return HttpResponse('Product Creation failed')
else:
return HttpResponse('Failed: Post requests only.')