这是表格
class LoginForm(forms.Form):
email = forms.EmailField(
label=("Email"),
widget=forms.TextInput(attrs={
'id': 'inputEmail',
'class': 'form-control inp',
'type': 'text',
'placeholder': 'your email'
}),
required=True
)
password = forms.CharField(
widget=forms.PasswordInput(
render_value=False,
attrs={
'id': 'inputPassword',
'class': 'form-control inp',
'type': 'password',
'placeholder': 'Password'
}
),
required=True
)
,这是表格的视图
class Home(View):
template_name = "sellers/seller_home.html"
form_class = LoginForm
def get(self, request , *args , **kwargs):
context = {}
login_form = LoginForm()
context['login_form'] = login_form
return render(request , "sellers/seller_home.html" , context)
def post(self , request , *args , **kwargs):
email = request.POST.get('email')
name = request.POST.get('store_name')
password = request.POST.get('password')
mobile = request.POST.get('mobile')
form = self.form_class(request.POST)
if request.is_ajax():
if email:
if User.objects.filter(email=email).exists():
return HttpResponse(json.dumps('True'))
else:
return HttpResponse(json.dumps('False'))
if mobile:
if User.objects.filter(mobile=mobile).exists():
return HttpResponse(json.dumps('True'))
else:
return HttpResponse(json.dumps('False'))
else:
if form.is_valid():
email = form.cleaned_data["email"]
password = form.cleaned_data["password"]
user = User.objects.get(email__iexact=email)
authenticated_user = authenticate(username=user.username , password=password)
if not authenticated_user:
raise ValidationError("Email or password is incorrect")
else:
login(request , authenticated_user)
return HttpResponseRedirect(reverse('dashboard'))
else:
return render(request , self.template_name , {'login_form' : form})
我面临的问题是,我无法将验证错误显示为模板中的标签。因为验证错误会引发错误。如何以更好的方式实现验证?
这里是追溯
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\views\generic\base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\generic\base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "C:\Users\lenovo\Desktop\Grooved2\grooved\src\sellers\views.py" in post
82. raise ValidationError("Email or password is incorrect")
Exception Type: ValidationError at /sellers/
Exception Value: [u'Email or password is incorrect']
答案 0 :(得分:3)
Django视图不处理验证错误。您应该使用ValidationError
或clean_<field>
种方式提升clean
。
请注意,Django已经有一个你可以使用的内置AuthenticationForm
。如果您查看其源代码,您可以在表单clean
方法中查看它如何调用authenticate
,而不是在视图中。
答案 1 :(得分:1)
您使用的是内置身份验证方法:
angular.module('myApp')
.component('myView', {
templateUrl: 'app/views/myview.html',
controller: myViewComponent,
controllerAs: "viewCtrlVM"
});
所以不需要提出authenticated_user = authenticate(username=user.username , password=password)
Django视图无法处理它。您应该使用clean方法来验证字段。