[英]Creating django form with null and blank field
I'm trying to create a form where both fields is optional however, i keep getting an error when setting null
and blank
.我正在尝试创建一个表单,其中两个字段都是可选的,但是,在设置
null
和blank
时我不断收到错误消息。 what am i doing wrong?我究竟做错了什么?
Error错误
super(CharField, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'blank'
forms.py表格.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
As @danielcorreia said you don't use blank
in a form, use required = False
instead.正如@danielcorreia 所说,您不要在表单中使用
blank
,而是使用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
The CharField
cunstructor dosent take blank
as an argument. CharField
cunstructor 将blank
作为参数。 You should use required = False
instead of using blank
and null
fields.您应该使用
required = False
而不是使用blank
和null
字段。 By defaylt required
is True
.默认
required
是True
。 To make your code work write:要使您的代码正常工作,请编写:
first_name = forms.CharField(label=("Fornavn"), strip=False, required=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.