django jquery-form .load()如果表单错误

我正在使用jquery.load()函数将表单加载到弹出窗口div,到目前为止它运行良好。 我想补充的是,当表单提交错误时,它会将错误标记表单加载回弹出div而不是重定向到它当前正在执行的实际表单页面。

有人建议我使用jquery-form ,我觉得它可以很好地工作。 我只是不知道如何实现它。

这是.load()函数:

$(document).ready(function(){ $(".create").on("click", function(){ $("#popupContact").load("/cookbook/createrecipe #createform"); }); }); 

这是加载表单的页面:

  

这是我的表单模板:

 

Create New Recipe

{% csrf_token %} {{ form.as_table }}

这是我尝试使用jquery-form:

  // wait for the DOM to be loaded $(document).ready(function() { var options ={ target: '.popup', }; $('#createrecipe').submit(function() { $(this).ajaxSubmit(options); return false; }); });  

createrecipe视图:

 def createrecipe(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/index/') else: if request.method == 'POST': print 1 form = RecipeForm(request.POST) if form.is_valid(): print 2 recipe = form.save(commit=False) recipe.original_cookbook = request.user.cookbooks.all()[0] recipe.pub_date = datetime.datetime.now() recipe.save() user = request.user cookbooks = user.cookbooks cookbook = cookbooks.all()[0] cookbook.recipes.add(recipe) return HttpResponseRedirect('/account') else: form = RecipeForm() return render_to_response('cookbook/createrecipe.html', {'form':form}, context_instance=RequestContext(request)) 

谢谢小吃鱼

因为你使用jquery,你应该通过ajax提交你的表单,否则你将被重定向:

  $('#createform form').submit(function(e) { e.preventDefault(); $.post("/your views url/", { data: $('#createform form').serialize(), },function(data){ //this is the successfunction //data is what your view returns} }); 

您的视图应该以json的forms返回错误,以便您可以在javascript中处理它们:

 from django.utils import simplejson def ajax_recipe(request): if request.method == 'POST': form = YourForm(request.POST) if form.is_valid(): form.save() return HttpResponse("ok") else: errors = form.errors return HttpResponse(simplejson.dumps(errors)) else: data = "error" return HttpResponse(data) 

使用该标记,您可以使用jquery post success函数将表单错误放在任何您想要的位置。

 if(data == "ok"){do something} // else error handling var errors = jQuery.parseJSON(data) if(errors.somefield){//place errors.somefield anywhere} 

请注意,代码未经过测试。 但这就是我的方式。

编辑

请注意,要使这项工作,您必须将自定义X-CSRFToken标头设置为每个XMLHttpRequest上的CSRF标记的值。 换句话说,从模板中的django文档复制并粘贴脚本: https : //docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

多数民众赞成你如何提出你的Form.py中的错误

 def clean_somefield(self): somefield = self.cleaned_data.get('some field') if not somefield: raise forms.ValidationError(u'This field is required.') 

我的javascript语法出错了一切都好