简体   繁体   English

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

[英]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 .我正在尝试创建一个表单,其中两个字段都是可选的,但是,在设置nullblank时我不断收到错误消息。 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而不是使用blanknull字段。 By defaylt required is True .默认requiredTrue To make your code work write:要使您的代码正常工作,请编写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM