为什么Django会出现KeyError?

问题描述 投票:1回答:1

我一直在查看Django文档,以获取如何将CSS类添加到模型表单输入的示例。但是,当我使用该解决方案时,Django引发了一个KeyError,我无法确定源代码,因为调试屏幕显示的代码行是模板中完全不相关的CSS类。

解决方案:

def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['title', 'content', 'category'].widget.attrs.update({'class': 'form-control'})
        self.fields['content'].widget.attrs.update(size='100', height='50')

错误消息:

KeyError at /new/

('title', 'content', 'category')

Request Method:     GET
Request URL:    http://localhost:8000/new/
Django Version:     2.1.7
Exception Type:     KeyError
Exception Value:    

('title', 'content', 'category')

Exception Location:     /home/bob/python-virtualenv/blog/bin/blog/posts/forms.py in __init__, line 11

提前致谢!

python django
1个回答
1
投票

您不能以这种方式使用多个键:

self.fields['title', 'content', 'category']

您必须单独查找它们:

self.fields['title']
self.fields['content']
...

或者在你的代码中:

for key in ['title', 'content', 'category']:
    self.fields[key].widget.attrs.update({'class': 'form-control'})

请注意,允许在Python中的字典中使用元组作为键:

>>> a = {}
>>> a['some','tuple'] = 'value'
>>> a
{('some', 'tuple'): 'value'}
© www.soinside.com 2019 - 2024. All rights reserved.