Django表示嵌套If - 第二个条件

时间:2018-01-26 12:07:14

标签: python django django-forms

我有一个django表单,用于检查邮政编码是否有效,如果有效,它将对允许传递的邮政编码执行检查。我不能让第二个条件在嵌套的if结构中工作(独立工作正常)。这是代码:

from django import forms
import requests

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

    def clean_pcode(self):
        pcode = self.cleaned_data['pcode'].lower()
        permitted = {'gu15','GF34','FG34','BT25'}
        url = 'https://api.postcodes.io/postcodes/{}/validate'.format(pcode)
        r = requests.get(url)
        is_correct = r.json()['result']
        if not is_correct:
            raise forms.ValidationError("Your postcode is invalid. Please re-enter a valid entry.")
            if not pcode[:4] in (permitted):
                raise forms.ValidationError("Apologies, but does not currently deliver to you postcode.")
                return pcode

1 个答案:

答案 0 :(得分:0)

修复缩进,以便第二个if statment和return语句在第一个if语句之外。

def clean_pcode(self):
    pcode = self.cleaned_data['pcode'].lower()
    permitted = {'gu15','GF34','FG34','BT25'}
    url = 'https://api.postcodes.io/postcodes/{}/validate'.format(pcode)
    r = requests.get(url)
    is_correct = r.json()['result']
    if not is_correct:
        raise forms.ValidationError("Your postcode is invalid. Please re-enter a valid entry.")
    if not pcode[:4] in (permitted):
        raise forms.ValidationError("Apologies, but does not currently deliver to you postcode.")
    return pcode

另外,您应该将切片从pcode[:4]更改为pcode[:-3]。这意味着如果您将3个字符的发布区域(例如GU1)添加到permitted集合中,您的代码仍然可以使用。

此外,由于您致电lower(),因此您需要确保permitted中的所有条目均为小写。就个人而言,我会使用upper()来规范化邮政编码。