【问题标题】:Django text in SmallIntegerField results in a KeyErrorSmallIntegerField 中的 Django 文本导致 KeyError
【发布时间】:2023-04-01 06:14:02
【问题描述】:

我使用 models.py 中的 models.Model、forms.py 中的 ModelForm 和 oldschool Django 模板创建了一个简单的 html 表单(没什么花哨的)

如果用户在数字字段中输入文本并提交表单,服务器会返回KeyError

示例:以下字段“高度”:

class DataRegistryPart2(models.Model):
    height = models.SmallIntegerField(blank=True, null=True)

将在模板中显示为html输入:

<input id="id_height" name="height" type="number">

我在 forms.py 中使用自定义验证:

...
def clean(self):
    cleaned_data = super(CreatePatient, self).clean()
    height = cleaned_data["height"] # <-- This is where the KeyError happens!

如果用户在输入字段中输入 文本十进制 数字并提交 html 表单,Django 会返回 KeyError。

如何防止这种情况发生(不使用 try/catch)。

谢谢!

【问题讨论】:

    标签: python django django-models django-forms


    【解决方案1】:

    如果您在字段中输入无效值,则该字段根据定义是不干净的,因此它不会出现在 cleaned_data 中;因此出现 KeyError。

    除非您需要此值与另一个字段组合进行一些验证,否则您应该在特定的clean_height 方法中执行您正在执行的任何操作;仅当值通过内置字段验证时才会调用此方法。

    【讨论】:

    • 感谢您的回答!听起来使用 clean 函数是一个非常糟糕的主意 - 用户很可能将无效数据输入到导致系统崩溃的表单中。也许我误解了一些东西,但我发现现在很难看到 clean 函数的用法。也许你可以详细说明?
    • 不,不是。正如我所说,它用于在多个领域进行验证;在这种情况下,您可以使用cleaned_data.get('fieldname') 访问可能缺失的值,而不会触发 KeyError。
    • 感谢您澄清这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 2017-02-26
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多