[英]Django render ModelForm with ajax response
I need to render a django modelform with the response of an ajax call. 我需要使用ajax调用的响应来呈现django模型。
What I actually do is: 我实际上所做的是:
I call an ajax function giving the model_pk = 0 to return me an empty form 我调用给定了model_pk = 0的ajax函数以返回一个空表格
$.ajax({ // create an AJAX call...
data: {'ubi_pk':0},
type: 'POST', // GET or POST
url: '{% url 'ubicacion_obtener_form' %}',
success: function(response,status) { // on success..
if (status == 'success'){
$('#form-nueva-ubicacion').html(response);
}
...
},
...
});
return false;
this is my view: 这是我的看法:
def ubicacion_obtener_form(request):
try:
ubi_pk = request.POST.get('ubi_pk',0)
if ubi_pk!='0':
ubi = Ubicacion.objects.get(pk=ubi_pk)
ubicacion_form = UbicacionForm(request.POST,instance=ubi)
form = render_to_string('ubicacion_form.html', {'ubicacion_form':ubicacion_form},
context_instance=RequestContext(request))
else:
ubicacion_form = UbicacionForm(request.POST)
form = render_to_string('ubicacion_form.html', {'ubicacion_form':ubicacion_form},
context_instance=RequestContext(request))
return HttpResponse(form,status=200)
except Ubicacion.DoesNotExist:
return HttpResponse(u'No existe la ubicación',status=400)
except Exception as e:
return HttpResponse('%s %s' % (e.message,e.args),status=500)
This is the ubicacion_form.html
template: 这是ubicacion_form.html
模板:
{% load crispy_forms_tags %}
{% csrf_token %}
{{ubicacion_form|crispy}}
When I give the ajax function an ID, my view should return the form with the data of the Model, with the fields with the data, BUT, when I try to get an empty form, it return me the form with "form errors", with those messages of *necessary fields and those horrible red colors. 当我给ajax函数一个ID时,我的视图应返回包含Model数据的表单,以及包含数据BUT的字段,当我尝试获取空表单时,它将返回带有“表单错误”的表单,带有*必填字段的消息和可怕的红色。
What am I doing wrong? 我究竟做错了什么? How can I get an empty form without the error messages? 如何获得没有错误消息的空白表格?
NOTE I am using crispy_forms
to render my forms with bootstrap theme 注意我正在使用crispy_forms
来呈现带有引导主题的表单
You're still passing in request.POST
when instantiating the supposedly-empty form in the else clause. 在else子句中实例化为空形式时,您仍在传递request.POST
。 Don't do that: just do ubicacion_form = UbicacionForm()
. 不要那样做: ubicacion_form = UbicacionForm()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.