I'm trying to create a form where both fields is optional however, i keep getting an error when setting null
and blank
. what am i doing wrong?
Error
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
null=True will make the field accept NULL values. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the database.
null is purely database-related, whereas blank is validation-related. If a field has blank=True , form validation will allow entry of an empty value. If a field has blank=False , the field will be required.
In order to make a field optional, we have to say so explicitly. If we want to make the pub_time field optional, we add blank=True to the model, which tells Django's field validation that pub_time can be empty.
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
As @danielcorreia said you don't use blank
in a form, use required = False
instead.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With