python - 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.')
视图.py
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()
你能试试这个吗?
推荐阅读
- wordpress - 无法在 Wordpress 页面模板中进行分页,已经尝试过很多次但都失败了
- entropy - 比较不同样本大小之间的熵
- python - 如何在 Apache Spark 的数据帧上运行 Python 中的正则表达式
- java - 休眠连接表问题
- c# - Linq 根据子类属性选择数组项
- python - Python 读取 sdf/mdl 坐标:如何读取直到遇到两个空格?
- python - 如何将sklearn管道步骤与不同的arity结合起来?
- python - 使用 numpy 实现线性回归
- android - 如何修复 React-Native Android affineFormats 错误
- node.js - 在 express js 中使用 mongoDB find()