'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. 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
Solution 1:[1]
If you want to save it as None in case when no data provided in the form for that field. You can do it with empty_value parameter to CharField (Django Docs):
field_name = forms.CharField(required=False, empty_value=None)
Note: You should save null to a char field ONLY if you want to distinguish between null and "" (blank) on that field. Otherwise, a nullable char field is not much recommended.
Solution 2:[2]
The CharField cunstructor dosent take blank as an argument. You should use required = False instead of using blank and null fields. By defaylt required is True. To make your code work write:
first_name = forms.CharField(label=("Fornavn"), strip=False, required=False)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GeekyShacklebolt |
| Solution 2 | Przemek |
