evhberijvbrdjvbej
evhberijvbrdjvbej

Reputation: 13

Why is Django showing a KeyError?

I've been looking at the Django docs for an example on how to add CSS classes to model form inputs. When I use the solution, though, Django raises a KeyError, and I can't really pinpoint the source, because the line of code the debug screen shows is a completely irrelevant CSS class in the template.

The solution:

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

The error message:

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

Thanks in advance!

Upvotes: 1

Views: 2363

Answers (1)

Bart Friederichs
Bart Friederichs

Reputation: 33521

You cannot use multiple keys in this way:

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

You will have to look them up separately:

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

Or in your code:

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

Note that it is allowed to use a tuple as key in a dictionary in Python:

>>> a = {}
>>> a['some','tuple'] = 'value'
>>> a
{('some', 'tuple'): 'value'}

Upvotes: 1

Related Questions