为什么Django显示一个钥匙室



我一直在查看django docs,以获取有关如何将CSS类添加到模型表单输入的示例。但是,当我使用解决方案时,django提出了一个键盘,我无法真正指出源,因为调试屏幕显示的代码行显示是模板中的完全无关的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

预先感谢!

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

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'}

最新更新