Django提升表单ValidationError不起作用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django提升表单ValidationError不起作用相关的知识,希望对你有一定的参考价值。
这可能是一个重复的问题,但我没有找到解决我的问题的方法。问题在于我的UserLoginForm验证。 “raise forms.ValidationError”不起作用,不会抛出错误。其他一切都完美无缺。
我的表单验证块
def clean(self):
cleanedData= super(UserLoginForm, self).clean()
username= cleanedData.get('username')
password = cleanedData.get('password')
if User.objects.filter(username=username).exists() is False:
print("User not available Validation should trigger")
raise forms.ValidationError('User does not exists.')
else:
user = authenticate(username=username, password=password)
if user is None:
print("Authentication Failed Validation should trigger")
raise forms.ValidationError('Invalid Credentials.')
views.朋友
def signin(request):
if request.method == 'POST':
form= UserLoginForm(request.POST)
if form.is_valid():
username= str(form.cleaned_data['username']).lower()
password= form.cleaned_data['password']
user= authenticate(username= username, password= password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse_lazy('testapp:index'))
else:
return HttpResponse('User Not Active')
else:
return HttpResponse('Login Unsuccessful.')
else:
return HttpResponse('Form not valid')
elif request.method == 'GET':
if request.user.is_authenticated:
return HttpResponseRedirect(reverse_lazy('testapp:index'))
else:
form= UserLoginForm()
return render(request, 'signin.html', {'form': form})
HTML模板
{% extends "base.html" %}
{% load static %}
{% block bodyblock %}
<div class="container">
<img src="{% static "images/face.png" %}" alt="image no found">
<div class="heading">
<h1>Login</h1>
</div>
<form action="" method="post" id="signinForm">
{% csrf_token %}
<div class="form-input">
<i class="fas fa-user"></i>
{{ form.username }}
</div>
{% if form.username.errors %}
<span>{{ form.username.errors }}</span>
{% endif %}
<div class="form-input">
<i class="fas fa-lock"></i>
{{ form.password }}
</div>
{% if form.password.errors %}
<span>{{ form.password.errors }}</span>
{% endif %}
{{ form.non_field_errors }}
{{ form.source.errors }}
{{ form.source }}
<div class="form-submit">
<input type="submit" value="Sign In">
</div>
</form>
</div>
{% endblock bodyblock %}
为了捕获错误,我在我的HTML模板中使用了全部3({{form.non_field_errors}},{{form.source.errors}},{{form.source}})。
我能够看到“用户不可用验证应该触发”和“验证失败验证应该触发”,但是引发VailidationError无法正常工作。
答案
# Validation
def clean(self):
cleaned_data = super(UserLoginForm, self).clean()
username = cleaned_data.get("username")
email = cleaned_data.get("email")
email_exist = User.objects.filter(email=email).exists()
username_exist = User.objects.filter(username=username).exists()
if username_exist:
raise forms.ValidationError('User Exists')
else:
raise forms.ValidationError('User does not exists')
return super(UserProfileForm, self).clean()
你能试试吗?
另一答案
正如@Daniel Roseman所建议的,用“return render(request,'signin.html',{'form':form})”替换“返回HttpResponse('表格无效')”,这解决了这个问题。
以上是关于Django提升表单ValidationError不起作用的主要内容,如果未能解决你的问题,请参考以下文章
如果引发 ValidationError,删除链接会在 Django 管理内联表单集中消失
Django绑定表单无效,但未引发ValidationError
从 django 模型的保存方法中引发 ValidationError?