gpt4 book ai didi

python - Django:当用户提交未完成的表单时如何引发异常?

转载 作者:太空狗 更新时间:2023-10-30 01:02:47 25 4
gpt4 key购买 nike

我有一个相对标准的注册表,如下所示:

class RegisterForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'username'}), initial='')
email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'email'}), initial='')
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'password'}), initial='')
password_repeat = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'retype password'}), initial='')

当用户忘记填写一个或多个字段时,我如何创建一个返回错误的干净方法? (即“您忘记填写电子邮件字段”)

我在 clean() 方法中尝试了以下两个选项(我将使用 password 和 password_repeat 字段作为示例):

password = self.cleaned_data['password']
password_repeat = self.cleaned_data['password_repeat']
# initial values are set to '' for all fields, see above.
if password == '':
raise forms.ValidationError("You forgot to type in a password.")
elif password_repeat == '':
raise forms.ValidationError("You forgot to retype your password.")

第一个选项返回:

在/homepage/出现KeyError

'密码'


try:
password = self.cleaned_data['password']
password_repeat = self.cleaned_data['password_repeat']
except KeyError(password):
raise forms.ValidationError("You forgot to fill in the password field.")

第二个选项返回:

UnboundLocalError at/homepage/

赋值前引用的局部变量'password'


如果您能提供一个允许检查剩余字段的解决方案(这样我就可以返回一个绑定(bind)到用户成功提交的数据的表单),则加分。

最佳答案

您可以使用 required 属性适用于所有 Field 类型,它会自动执行此类验证。所以你的代码看起来像:

class RegisterForm(forms.Form):
username = forms.CharField(
widget = forms.TextInput(attrs = {'placeholder': 'username'}),
required = True)
email = forms.EmailField(
widget = forms.TextInput(attrs = {'placeholder': 'email'}),
required = True)
password = forms.CharField(
widget = forms.PasswordInput(attrs = {'placeholder': 'password'}),
required = True)
password_repeat = forms.CharField(
widget = forms.PasswordInput(attrs = {'placeholder': 'retype password'}),
required = True)

注意:我认为您可以省略那些 initial = ''参数也是如此,如上所示。

我实际上不确定为什么你会收到你在问题中提到的错误,也许你可以从你的 views.py 发布相关代码?可能是因为您需要返回 cleaned_data在任何 clean 的末尾您实现的方法。

我还想说您对 clean 的使用方法不太对。如果您引用关于 form and field validation 的文档的这一页您会看到要验证单个字段,您使用特定的 clean_<fieldname>方法例如clean_password_repeat .使用 clean当验证同时涉及多个字段时,方法是合适的,您可能喜欢使用的一个示例是检查两个密码字段的输入是否匹配。

class RegisterForm(forms.Form):
# field definitions (above)

def clean(self):
password = self.cleaned_data['password']
password_repeat = self.cleaned_data['password_repeat']
if password != password_repeat:
raise forms.ValidationError(u"Passwords do not match.")
return cleaned_data

注意:代码未经测试。

希望对您有所帮助!

关于python - Django:当用户提交未完成的表单时如何引发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13502342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com