使用null和空白字段创建django表单

时间:2017-11-21 20:50:58

标签: python django

我正在尝试创建一个表单,其中两个字段都是可选的,但是在设置nullblank时我一直收到错误消息。我做错了什么?

错误

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

2 个答案:

答案 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而不是blanknull字段。默认requiredTrue。为了使您的代码能够工作:

first_name = forms.CharField(label=("Fornavn"), strip=False, required=False)