我发现similar question有点过时了。我想知道如果不使用另一个图书馆是否可行。
目前,forms.ValidationError
将触发form_invalid
,它只返回带有错误和状态代码的JSON响应。
我有一个ajax表单,并想知道在ajax表单提交时是否可以在表单字段上发生通常的django字段验证。
我的表单触发错误:
class PublicToggleForm(ModelForm):
class Meta:
model = Profile
fields = [
"public",
]
def clean_public(self):
public_toggle = self.cleaned_data.get("public")
if public_toggle is True:
raise forms.ValidationError("ERROR")
return public_toggle
ajax的相应View的mixin:
from django.http import JsonResponse
class AjaxFormMixin(object):
def form_invalid(self, form):
response = super(AjaxFormMixin, self).form_invalid(form)
if self.request.is_ajax():
return JsonResponse(form.errors, status=400)
else:
return response
def form_valid(self, form):
response = super(AjaxFormMixin, self).form_valid(form)
if self.request.is_ajax():
print(form.cleaned_data)
print("VALID")
data = {
'message': "Successfully submitted form data."
}
return JsonResponse(data)
else:
return response
观点:
class PublicToggleFormView(AjaxFormMixin, FormView):
form_class = PublicToggleForm
success_url = '/form-success/'
在浏览器控制台上,错误将作为400 Bad Request,然后是具有正确ValidationError消息的responseJSON。
编辑:任何方式让字段验证显示客户端?
编辑:附加代码:
前端收到的数据的完整副本:
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
abort:
ƒ (a)
always:
ƒ ()
catch:
ƒ (a)
done:
ƒ ()
fail:
ƒ ()
getAllResponseHeaders:
ƒ ()
getResponseHeader:
ƒ (a)
overrideMimeType:
ƒ (a)
pipe:
ƒ ()
progress:
ƒ ()
promise:
ƒ (a)
readyState:
4
responseJSON:
public:
["ERROR"]
__proto__:
Object
responseText:
"{"public": ["ERROR"]}"
setRequestHeader:
ƒ (a,b)
state:
ƒ ()
status:
400
statusCode:
ƒ (a)
statusText:
"Bad Request"
then:
ƒ (b,d,e)
__proto__:
Object
模板中的表单使用Django的{{as_p}}:
进行渲染{% if request.user == object.user %}
Make your profile public?
<form class="ajax-public-toggle-form" method="POST" action='{% url "profile:detail" username=object.user %}' data-url='{% url "profile:public_toggle" %}'>
{{public_toggle_form.as_p|safe}}
</form>
{% endif %}
Javascript:
$(document).ready(function(){
var $myForm = $('.ajax-public-toggle-form')
$myForm.change(function(event){
var $formData = $(this).serialize()
var $endpoint = $myForm.attr('data-url') || window.location.href // or set your own url
$.ajax({
method: "POST",
url: $endpoint,
data: $formData,
success: handleFormSuccess,
error: handleFormError,
})
})
function handleFormSuccess(data, textStatus, jqXHR){
// no need to do anything here
console.log(data)
console.log(textStatus)
console.log(jqXHR)
}
function handleFormError(jqXHR, textStatus, errorThrown){
// on error, reset form. raise valifationerror
console.log(jqXHR)
console.log("==2" + textStatus)
console.log("==3" + errorThrown)
$myForm[0].reset(); // reset form data
}
})
答案 0 :(得分:1)
您将JSON格式的错误响应格式化为{field_key: err_codes, ...}
。然后你需要做的就是在每个渲染的表单字段下创建<div class="error" style="display: none;"></div>
,这可以通过字段手动渲染表单字段来完成,或者你可以在表单下面创建一个错误的块,如:
<div id="public_toggle_form-errors" class="form-error" style="display: none;"><div>
在表单中添加一些css:
div.form-error {
margin: 5px;
-webkit-box-shadow: 0px 0px 5px 0px rgba(255,125,125,1);
-moz-box-shadow: 0px 0px 5px 0px rgba(255,125,125,1);
box-shadow: 0px 0px 5px 0px rgba(255,125,125,1);
}
所以它看起来好像发生了错误,然后添加到handleFormError函数代码:
function handleFormError(jqXHR, textStatus, errorThrown){
...
$('#public_toggle_form-errors').text(textStatus.["public"]);
$('#public_toggle_form-errors').show();
...
}
我想你会明白这个想法。