[Django]-Django CharField not defaulting to empty string

3๐Ÿ‘

โœ…

# Run this through an address parser - this returns a dictionary of address components
# Optional fields are returned as None if not present
components = parser.parse(raw_address)

This explicitly sets the value to None, which is directly translated to NULL in the database. You should remove all keys which have value None or replace the value with '' instead:

components = {k: v for k, v in components.items() if v is not None}

This will only set the non-empty components, and the others will default to an empty string instead of NULL.

๐Ÿ‘คknbk

0๐Ÿ‘

In the quoted text you pasted, a bit after it states:

you will also need to set blank=True if you wish to permit empty values in forms, as the null parameter only affects database storage (see blank).

For strings you should use blank=True

class MyModel(models.Model):
    required_string = models.CharField()
    optional_string = models.CharField(blank=True, default="")
๐Ÿ‘คpetkostas

Leave a comment