表单验证错误将我发送到 ValidationerError 页面
forms validationerror sends me to a ValidationerError page
几天来我一直在为这个问题苦苦挣扎。正如您所见,验证错误有效,但我希望错误显示在表单中,而不是将用户重定向到 ValidationError 页面。我错过了什么?我使用 django Alluth
def custom_signup(self, request, user):
user.profile.pid = self.cleaned_data[_("pid")]
data = User.objects.filter(profile__pid=user.profile.pid)
if data.exists():
raise forms.ValidationError(
_('This user exists in our system. Please try another.'),
code='unique_pid'
)
else:
user.save()
return user
好的,首先您需要创建一个自定义注册表单,我在
中详细介绍了如何完成
您看到的是 500 页,处于调试模式(因此您可以获得有关所发生情况的所有信息)。你看到这个的原因是你报错了。
您想要做的是向表单添加一个错误,作为该表单验证的一部分。
创建自定义注册表单后,您可以将验证添加为表单 clean
方法的一部分;
def clean(self):
"""
Clean the form
"""
cleaned_data = super().clean()
pid = self.cleaned_data["pid"]
if User.objects.filter(profile__pid=pid).exists():
self.add_error(
'pid',
_('This user exists in our system. Please try another.'),
)
return cleaned_data
请注意,您还使用翻译 (_("")
) 来访问表单的 cleaned_data
- 您不需要这样做。
几天来我一直在为这个问题苦苦挣扎。正如您所见,验证错误有效,但我希望错误显示在表单中,而不是将用户重定向到 ValidationError 页面。我错过了什么?我使用 django Alluth
def custom_signup(self, request, user):
user.profile.pid = self.cleaned_data[_("pid")]
data = User.objects.filter(profile__pid=user.profile.pid)
if data.exists():
raise forms.ValidationError(
_('This user exists in our system. Please try another.'),
code='unique_pid'
)
else:
user.save()
return user
好的,首先您需要创建一个自定义注册表单,我在
您看到的是 500 页,处于调试模式(因此您可以获得有关所发生情况的所有信息)。你看到这个的原因是你报错了。
您想要做的是向表单添加一个错误,作为该表单验证的一部分。
创建自定义注册表单后,您可以将验证添加为表单 clean
方法的一部分;
def clean(self):
"""
Clean the form
"""
cleaned_data = super().clean()
pid = self.cleaned_data["pid"]
if User.objects.filter(profile__pid=pid).exists():
self.add_error(
'pid',
_('This user exists in our system. Please try another.'),
)
return cleaned_data
请注意,您还使用翻译 (_("")
) 来访问表单的 cleaned_data
- 您不需要这样做。