Home > Blockchain >  Why does adding more fields to this widget lead to a keyError?
Why does adding more fields to this widget lead to a keyError?

Time:12-02

Edit: I can see this is getting downvotes: I'm just trying to learn and I havent found a clear explanation of why this doesnt work. If you can downvote because you think its a stupid question why not take the time to explain?

I'm working on a form in my Django project. I wanted to add a bootstrap class to my input fields. I tried to do this with the following code:

class CategoryForm(ModelForm):
    class Meta:
        model = Category
        fields = '__all__'

        labels = {
            "sub_category":"Sub category (if any):"
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['category_name','sub_category','category_info','category_video'].widget.attrs.update({'class':'form-control'})

But when I load the page I get this:

KeyError at /academy/category_form
('category_name', 'sub_category', 'category_info', 'category_video')

Is this not possible? Do I have to add a new line for every field in my form? So like this:

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['category_name'].widget.attrs.update({'class':'form-control'})
        self.fields['sub_category'].widget.attrs.update({'class':'form-control'})
        self.fields['category_info'].widget.attrs.update({'class':'form-control'})
        ....

This would make for some long lines of code if I have to do this for every form which does not make sense of follow DRY.

CodePudding user response:

Within the form fields is a dictionary containing the form fields. It is not doing what you expect it to do ...your list of keys is interpreted as a tuple and that tuple is not in the form fields contained, that results in the mentioned KeyError.

Now to your attempt to not repeat yourself ... you can use a loop to avoid this:

for key in ('category_name', 'sub_category', 'category_info', 'category_video'):
    self.fields[key].widget.attrs.update({'class':'form-control'})
  • Related