亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 Django 顯示 KeyError?

為什么 Django 顯示 KeyError?

牧羊人nacy 2021-11-23 18:08:28
我一直在查看 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'}


查看完整回答
反對 回復 2021-11-23
  • 1 回答
  • 0 關注
  • 787 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號