我有一个ajax登录视图。我可以登录确定但是当我登录不正确时我的json返回: {“errors”:{}} 我的观点如下:
def ajaxlogin(request):
from forms import LoginForm
form = LoginForm(request.POST)
logged_in = False
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if request.is_ajax() and user is not None:
login(request, user)
logged_in = True
return HttpResponse(simplejson.dumps({'redirect' : 'true'}), content_type='application/json')
else:
return HttpResponse(simplejson.dumps({'errors': dict(form.errors.items())}), content_type='application/json')
有什么想法吗?
如果我使用不启用js的登录功能,表单将显示所有相关的错误消息。
我的LoginForm:
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
class LoginForm(AuthenticationForm):
username = forms.CharField(min_length=5, max_length=30,error_messages={'required':_("please enter a username"), 'min_length':_("username must be at least 5 characters"), 'max_length':_("username must be at less than 30 characters")})
password = forms.CharField(min_length=6, error_messages={'required':_("please enter a password"), 'min_length':_("password must be at least 6 characters")})
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if username and password:
self.user_cache = authenticate(username=username, password=password)
if self.user_cache is None:
raise forms.ValidationError(_("you have entered an incorrect username and/or password"))
elif not self.user_cache.is_active:
raise forms.ValidationError(_("This account is inactive."))
self.check_for_test_cookie()
return self.cleaned_data
答案 0 :(得分:2)
您尚未向我们展示您的LoginForm的样子。假设它只有两个CharField
,只要你提供了用户名和密码,我就不会发现任何错误。
要显示无效的用户名和密码组合的错误,您的表单必须包含用于验证登录数据的逻辑。
幸运的是,你自己没有写过这个,你可以使用内置AuthenticationForm
的Django。如果用户名和密码无效,则会返回错误。
from django.contrib.auth.forms imoirt AuthenticationForm
from django.contrib.auth import login as auth_login
# in the view
if request.method == "POST":
form = AuthenticationForm(data=request.POST)
if form.is_valid():
# if the form is valid, the user has provided a valid
# username and password. We can get the user with the
# form.get_user method and log them in
auth_login(request, form.get_user())
# return suitable ajax responses
答案 1 :(得分:0)
尝试类似:
return HttpResponse(simplejson.dumps({'errors': form.errors.as_text()}), content_type='application/json')