python - Django错误: TypeError: __init__() got an unexpected keyword argument 'attrs'

标签 python python-3.x django django-forms django-widget

我正在尝试创建一个表单,从用户那里获取某些详细信息。

我已经在 forms.py 中定义了字段,并且还使用 django 定义了其他属性,例如 placeholdercss class小部件系统。但它向我显示了一个 TypeError:

TypeError: __init__() got an unexpected keyword argument 'attrs'

以下是我的代码:

models.py

from django.db import models

class Contact(models.Model):
    your_name = models.CharField(max_length=100) 
    your_email = models.EmailField()
    your_subject = models.CharField(max_length=100)
    your_comment = models.TextField(max_length=200)
 
 def __str__(self):
    return self.name

forms.py

from django.forms import ModelForm, TextInput, TextInput, EmailField
from .models import Contact

class ContactForm(ModelForm):
    class Meta:
        model = Contact
        fields = ('your_name', 'your_email', 'your_subject', 'your_comment')
        widgets = {
            'your_name' : TextInput(attrs={'placeholder': 'Name *', 'class': 'form-control'}),
            'your_email' : EmailField(attrs={'placeholder': 'Email *', 'class': 'form-control'}),
            'your_subject' : TextInput(attrs={'placeholder': 'Subject *', 'class': 'form-control'}),
            'your_comment' : Textarea(attrs={'placeholder': 'Comment *', 'class': 'form-control'}),
        }

我已阅读 Django docs for Overriding default fields还有这个问题init() got an unexpected keyword argument 'attrs'但无法修复错误。

我对 Python 和 Django 很陌生,希望得到任何帮助,谢谢。

最佳答案

错误在行

'your_email' : EmailField(attrs={}),

EmailField 是一个字段,而不是一个小部件。 EmailField 的默认小部件是 EmailInput

您需要提供一个小部件:

'your_email' : EmailInput(attrs={}),

关于python - Django错误: TypeError: __init__() got an unexpected keyword argument 'attrs' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41323764/

相关文章:

python - 创建多维数组的函数

python - 从列表列表中的项目形成数组

python - 为什么不 pip 安装 django 2.x?

python - 如何让 pyparser 以特定形式工作

python - 可以在 python 中创建类似 bash 的 shell,即 : Bash replacement?

python - Django:显示名字和姓氏

django - 如何捕获匿名用户的 session key (django 1.6)

python - 使用OpenCV检测两个接近相似的视频

javascript - 通过HTML代码控制python代码

Django 无法导入模型