Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django CharField blank vs default empty

What is the difference between this two fields in a Django app? What behaviour should I expect?

field_a = CharField(max_length=50, verbose_name='field_a', blank=True)
field_b = CharField(max_length=50, verbose_name='field_b', blank=True, default='')
like image 325
MatheusJardimB Avatar asked Nov 18 '15 02:11

MatheusJardimB


People also ask

What is the difference between blank and null in Django?

In Very simple words, Blank is different than null. null is purely database-related, whereas blank is validation-related(required in form). If null=True , Django will store empty values as NULL in the database . If a field has blank=True , form validation will allow entry of an empty value .

What is the difference between Blank true and null true?

The fundamental difference between these two is that null controls the validation at the database level, and blank is used during form field validation at the application level. By default all fields are required. In order to make a field optional, we have to say so explicitly.

What does CharField mean in Django?

CharField is a string field, for small- to large-sized strings. It is like a string field in C/C+++. CharField is generally used for storing small strings like first name, last name, etc. To store larger text TextField is used. The default form widget for this field is TextInput.

Is null false by default Django?

null. If True , Django will store empty values as NULL in the database. Default is False .


1 Answers

If default value is not given, empty string is used for CharField according to the following code (taken from django/db/models/fields/__init__.py source):

def get_default(self):
    """
    Returns the default value for this field.
    """
    if self.has_default():
        if callable(self.default):
            return self.default()
        return self.default
    if (not self.empty_strings_allowed or (self.null and
               not connection.features.interprets_empty_strings_as_nulls)):
        return None
    return ""

So they should behave same.

like image 143
falsetru Avatar answered Nov 02 '22 01:11

falsetru