Django-allauth-如何从Ajax获取表单错误? [英] Django-allauth - How do I get the form errors from Ajax?
问题描述
使用django-allauth,如何通过AJAX登录获取表格错误?
Using django-allauth, how do I obtain form errors via AJAX login?
我将这个视图与我的/signup/
网址一起使用:
I am using this view with my /signup/
url:
from allauth.account.views import SignupView
方便地,它接受我的Ajax呼叫:
Conveniently, it accepts my Ajax call:
var signupForm = function(token) {
$.ajax({ url:"/signup/",
type:"POST",
data: {
"email": $('#user').val(),
"password1": $('#pass1').val(),
"password2": $('#pass2').val()
},
success: function (){
location.href = '/';
window.location.reload(true);
},
error:function (er) {
alert("signup failure...",er);
}
});
};
如果表单有问题,它会很不方便地返回:
Inconveniently, if there is a problem with the form, it returns:
错误400:请求错误
error 400: Bad Request
这让我不知道为什么登录失败.我希望能够向用户传达发生了什么情况.她的密码有问题吗?她的电子邮件地址是否已经注册?
This gives me no idea why a login has failed. I would like to be able to convey to the user what happened. Was it a problem with her password? Was her email address already registered?
我可以使用all-auth来完成此操作,还是需要通过javascript编写自己的验证?
Can I accomplish this with all-auth, or do I need to write my own validation from javascript?
推荐答案
我找不到受支持的解决方案,因此被黑了:
I could not find a supported solution, so I hacked it:
from django.http import JsonResponse
from allauth.account.views import SignupView, _ajax_response
class AjaxSignUpView(SignupView):
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
response = self.form_valid(form)
return _ajax_response(
self.request, response, form=form, data=self._get_ajax_data_if())
else:
return JsonResponse({'errors': form.errors})
这篇关于Django-allauth-如何从Ajax获取表单错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!