我一直在查看 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: GETRequest URL: http://localhost:8000/new/Django Version: 2.1.7Exception Type: KeyErrorException Value: ('title', 'content', 'category')Exception Location: /home/bob/python-virtualenv/blog/bin/blog/posts/forms.py in __init__, line 11提前致謝!
1 回答
SMILET
TA貢獻1796條經驗 獲得超4個贊
您不能以這種方式使用多個鍵:
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'}
添加回答
舉報
0/150
提交
取消
