gpt4 book ai didi

django - 为什么 Django 会在此表单验证中抛出 KeyError?

转载 作者:行者123 更新时间:2023-12-04 13:50:25 25 4
gpt4 key购买 nike

代码如下:

...

class Meta:
model = Card

def clean_video_url(self):
video_url = self.cleaned_data['video_url']
if video_url != '' and len(video_url) != YOUTUBE_VIDEO_URL_LENGTH:
pos = string.find(video_url, YOUTUBE_VIDEO_URL_IDENTIFIER)
identifier_length = len(YOUTUBE_VIDEO_URL_IDENTIFIER)
if pos == -1:
raise forms.ValidationError(_('youtube-url-not-valid'))
video_url = video_url[pos+identifier_length:pos+identifier_length+YOUTUBE_VIDEO_URL_LENGTH]
return video_url

...

def clean(self):
video_url = self.cleaned_data['video_url']
field1 = self.cleaned_data['field1']
if video_url == '' and field1 == '':
raise forms.ValidationError(_('must-fill-video-url-or-front'))
return self.cleaned_data

最令人不安的是它几乎在所有情况下都有效(提交并持久化在数据库中)。当我在 video_url 字段 中写入“aeuchah”之类的虚拟文本时,它不起作用,而是抛出:

Exception Type: KeyError
Exception Value:
'video_url'

我重新阅读了我的 clean_video_url 方法,并使用 pdb.set_trace 等调试工具查看变量是什么,但我找不到问题所在。

更新:正如 Marius Grigaitis 和 Davide R. 所说,clean 方法在所有单独的字段方法完成后调用。 clean_video_url 引发了 ValidationError 并且没有返回任何内容,因此 clean 方法找不到任何可用的方法并引发了 KeyError。

最佳答案

clean() 方法中使用它之前,您应该始终检查 cleaned_data 中是否存在该键。如果先前的验证未通过,则不能保证值存在于 cleaned_data 数组中。

文档:https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

By the time the form’s clean() method is called, all the individual field clean methods will have been run (the previous two sections), so self.cleaned_data will be populated with any data that has survived so far. So you also need to remember to allow for the fact that the fields you are wanting to validate might not have survived the initial individual field checks.

关于django - 为什么 Django 会在此表单验证中抛出 KeyError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15396179/

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