简体   繁体   中英

django form custom clean gives keyerror

I am using a custom clean on a form I made. But then some weird things happen If my input data is valid. it works fine. However when it is not correct, I get a KeyError at key_ID in the clean method. Also, if I add print statements in the clean_key_ID and clean_verification_code, these don't show up in my console.

My form:

class ApiForm(forms.Form):

    key_ID = forms.CharField(min_length=7, max_length=7, required=True)
    verification_code = forms.CharField(
        min_length=64,
        max_length=64,
        required=True,
    )

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop("user")
        super(ApiForm, self).__init__(*args, **kwargs)

    def clean_key_ID(self):
        data = self.cleaned_data['key_ID']
        try:
            int(data)
        except ValueError:
            raise forms.ValidationError("Should contain 7 numbers")
        return data

    def clean_verification_code(self):
        data = self.cleaned_data['verification_code']
        if not re.match("^[A-Za-z0-9]*$", data):
            raise forms.ValidationError(
                "Should only contain 64 letters and numbers"
            )
        return data

    def clean(self):
        key = self.cleaned_data['key_ID']
        vcode = self.cleaned_data['verification_code']

        if Api.objects.filter(key=key, vcode=vcode, user=self.user).exists():
            raise forms.ValidationError(
                "This key has already been entered, try to update it"
            )

        #connect with api and validate key
        api = api_connect()
        auth = api.auth(keyID=key, vCode=vcode)
        try:
            keyinfo = auth.account.APIKeyInfo()
        except RuntimeError:
            raise forms.ValidationError("Invallid data, cannot connect to api")

in my view I get my form in the normal way:

view:

api_form = ApiForm(request.POST or None, user=request.user)
if request.POST and api_form.is_valid():
    #do things with form

I am lost and have no clue where this error is coming from. My form is rendered in the normal way {{api_form}}. I have already tried removing the underscores in my field names. But the error remains

If key_ID is invalid, then it will not be in self.cleaned_data in your clean method. You have to change your clean method to handle this, for example:

def clean(self):
    key = self.cleaned_data.get('key_ID')
    if not key:
        # early return
        return
    # rest of method as before
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM