【问题标题】:__init__() got an unexpected keyword argument 'attrs'__init__() 得到了一个意外的关键字参数“attrs”
【发布时间】:2013-05-05 03:33:31
【问题描述】:

forms.py

class ImportExcelForm(Form):
    file  = forms.FileField(attrs={'class':'rounded_list',})

我正在尝试在表单中将 css 类添加到我的filefield。我收到此错误"__init__() got an unexpected keyword argument 'attrs'"

我做错了什么。

谢谢

【问题讨论】:

    标签: django django-forms django-templates


    【解决方案1】:

    attrs 不是字段的参数,而是小部件的参数。

    file = forms.FileField(widget=forms.FileInput(attrs={'class': 'rounded_list'}))
    

    请注意,某些浏览器不允许对文件输入进行样式设置。

    【讨论】:

    • 我试过你的回答,得到这个错误“在模块 event.views 中尝试了 contact_list。错误是:'module' 对象没有属性 'FileWidget'”
    • 抱歉,应该是FileInput,已更正。
    • 为什么要隐藏按钮?那么就没有办法选择和上传文件了。
    • 应该是forms.FileField 吗?
    【解决方案2】:

    尽管@Daniel Roseman 发布的解决方案也是 Django 文档中推荐的解决方案,但它仍然对我不起作用。对我有用的是:

    class ImportExcelForm(Form):
        file  = forms.FileField()
        file.widget.attrs.update({'class': 'rounded_list'})
    

    【讨论】:

    • 这很有帮助,因为@Daniel 的某些解决方案对我不起作用:type = forms.ChoiceField(widget=forms.ChoiceField(attrs={'disabled': 'disabled'})) 但此表单有效type = forms.ChoiceField() type.widget.attrs.update({'disabled': 'disabled'})
    猜你喜欢
    • 2020-06-15
    • 2017-05-10
    • 2015-06-08
    • 2021-03-17
    • 2016-06-05
    • 2020-08-20
    • 2021-09-20
    • 2014-05-12
    • 2021-12-30
    相关资源
    最近更新 更多