def respond_error(request, form, message, code, template_name='news/formerror.html'):
"""
Return either a JSON or HTML error response
@param request: the request
@param form: the bound form object
@param message: the error message
@param code: the HTTP status code
@param template_name: the template name in case of HTML response
@return: HttpResponse object
"""
if request.is_ajax():
return HttpResponseJSON({
'status': 'error',
'errors': [message],
'errors_by_field': {NON_FIELD_ERRORS: [message]}
}, code)
else:
form.add_error(None, message)
return render(request, template_name, {'form': form}, status=code)
评论列表
文章目录