我正在尝试创建一个表单,其中两个字段都是可选的,但是在设置null
和blank
时我一直收到错误消息。我做错了什么?
错误
super(CharField, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'blank'
forms.py
class EditProfile(forms.Form):
"""
A form that lets a user change their profile information
"""
first_name = forms.CharField(
label=("Fornavn"),
strip=False,
blank=True,
null=True
)
last_name = forms.CharField(
label=("Efternavn"),
strip=False,
blank=True,
null=True,
)
def __init__(self, user, *args, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
def save(self, commit=True):
first_name = self.cleaned_data["first_name"]
last_name = self.cleaned_data["last_name"]
self.user.first_name = first_name
self.user.last_name = last_name
if commit:
self.user.save()
return self.user
答案 0 :(得分:1)
由于@danielcorreia表示你不在表格中使用“空白”,而是使用“required = False”。
class EditProfile(forms.Form):
"""
A form that lets a user change their profile information
"""
first_name = forms.CharField(
label=("Fornavn"),
strip=False,
required=False
)
last_name = forms.CharField(
label=("Efternavn"),
strip=False,
required=False
)
def __init__(self, user, *args, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
def save(self, commit=True):
first_name = self.cleaned_data["first_name"]
last_name = self.cleaned_data["last_name"]
self.user.first_name = first_name
self.user.last_name = last_name
if commit:
self.user.save()
return self.user
答案 1 :(得分:0)
CharField
cunstructor dosent以blank
为参数。您应该使用required = False
而不是blank
和null
字段。默认required
是True
。为了使您的代码能够工作:
first_name = forms.CharField(label=("Fornavn"), strip=False, required=False)