Django窗体,如何使用startswith验证窗体

2024-09-24 00:35:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图找出如何让下面的代码位工作,使一切以元组开始是有效的,例如,如果邮政编码'GU15 56L'是输入它允许邮政编码。目前只有GU15部件在工作(对于本例)。比如从哪里开始,但不确定从哪里开始。你知道吗

class PostCodeForm (forms.Form):
    pcode = forms.CharField()

    def clean_pcode(self):
        permitted = {'GU15','GF34','FG34','BT25'}
        pcode = self.cleaned_data['pcode'].lower()
        if not pcode in (permitted):
            raise forms.ValidationError("Apologies, but does not currently deliver to you postcode.")
        return pcode

提前谢谢你的帮助


Tags: 代码selfform部件notformsclass元组
2条回答

您只需检查是否允许前4个字符:

if not pcode[:4] in permitted:
    raise forms.ValidationError("Apologies, but does not currently deliver to you postcode.")

或者

if any([pcode.startswith(code) for code in permitted]) is False:
    raise forms.ValidationError("Apologies, but does not currently deliver to you postcode.")
if not pcode.startswith(tuple(permitted)):
    raise ValueError()

但是您使用self.cleaned_data['pcode'].lower(),并且您的集合包含所有大写单词。试试self.cleaned_data['pcode'].upper()

相关问题 更多 >