我想用ajax汇总模型表单并使用模型表单验证消息:
class ComplaintForm(forms.ModelForm):
class Meta:
model = Complaint
fields = [
'title','body'
]
def clean_body(self):
form_data = self.cleaned_data
body = self.cleaned_data.get('body', False)
if len(body) < 2:
raise forms.ValidationError(u'Please Add Complaint')
return body
def clean(self):
cd = self.cleaned_data
return cd
在我看来:
def forms(request):
form = ComplaintForm()
if request.method == "POST":
if request.is_ajax():
form = ComplaintForm(request.POST)
if form.is_valid():
c = form.save(commit=False)
c.user_ip = get_client_ip(request)
c.user = request.user
c.news = news
c.save()
data = serializers.serialize('json', [c,])
else:
data = json.dumps([v for k,v in form.errors.items()])
return HttpResponseBadRequest(data, mimetype='application/json')
return HttpResponse(data, mimetype='application/json')
else:
form = ComplaintForm()
return render_to_response('main/form.html', {'form': form},
context_instance=RequestContext(request))
但是,我的问题是如何通过HttpResponseBadRequest发送数据? 我的js是:
$('.complaintform').submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/form/",
dataType: "json",
data: $(this).serialize(),
success: function(data) {
$('p').html('ok');
},
error: function(data) {
//how could i insert model form errors here?
}
});
});
答案 0 :(得分:1)
编辑我的回答。我最初误解了你的问题。
试试这个:
$('.complaintform').submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/form/",
dataType: "json",
data: $(this).serialize(),
success: function(data) {
$('p').html('ok');
},
statusCode: {
400: function() {
var items = [];
$.each( data, function( val ) {
items.push( val );
});
$('p').html(items.join(""));
}
}
});
});
如果这不起作用,则一个肮脏的解决方法是:
1)在视图中:
else:
data = json.dumps([v for k,v in form.errors.items()] + ['failed'])
return HttpResponseBadRequest(data, mimetype='application/json')
2)在javascript中:
success: function(data) {
if jQuery.inArray("failed", data) {
data.splice("failed", 1);
var items = [];
$.each( data, function( val ) {
items.push( val );
});
$('p').html(items.join(""));
} else {
$('p').html('ok');
}
},
如果由于一些奇怪的原因,jquery认为你的HttpResponse是'成功',那将会奏效。