我正在尝试创建一个表单,以便我从用户那里获得某些详细信息。
我在forms.py
中定义了字段,我还使用django widget
系统定义了其他属性,例如占位符和 css类 。但是它向我展示了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的新手,非常感谢任何帮助,谢谢。
答案 0 :(得分:2)
错误在行
'your_email' : EmailField(attrs={}),
EmailField
是一个字段,而不是一个小部件。 EmailField
的默认小部件为EmailIput
。
您需要提供一个小部件:
'your_email' : EmailInput(attrs={}),
答案 1 :(得分:1)
TL; DR :EmailField
只是一个Field
,如果您尝试过,我只能设置为小工具在下面的问题中,您需要EmailInput
这是EmailField
的小部件。
首先,TextInput
和Textarea
接受attrs
中的关键字参数__init__
。所以,这些都很好。
看看这一行:
EmailField(attrs={'placeholder': 'Email *', 'class': 'form-control'}),
EmailField
是CharField
的子类,后者又是Field
的子类。在整个层次结构中,attrs
将一直传递到Field
,但不会接受attrs
。
此处参考__init__
的{{1}}:
Field
def __init__(self, required=True, widget=None, label=None, initial=None,
help_text='', error_messages=None, show_hidden_initial=False,
validators=(), localize=False, disabled=False, label_suffix=None):
的{{1}}:
__init__
CharField
的{{1}}:
def __init__(self, max_length=None, min_length=None, strip=True, empty_value='', *args, **kwargs)
....
super(CharField, self).__init__(*args, **kwargs)
# attrs is passed to Field -> error
接受 小部件 参数,您可以在其中放置 接受__init__
关键字的小部件。
答案 2 :(得分:0)
from django.forms import ModelForm
from django import forms
from .models import Contact
class UserForm(ModelForm):
class Meta:
model = Contact
fields = ('sender_name','sender_email')
widgets = {
'sender_name': forms.TextInput(attrs={'placeholder': 'Enter sender name'}),
}
导入表单,并使用访问表单字段。运算符