Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelForm not saving BooleanField default value

I have the following Model:

class TransType(models.Model):
    typeName = models.CharField(max_length=200)
    isActive = models.BooleanField(default=True, blank=True)

    def __str__(self):
        return self.typeName

Whenever I am creating a new object without specifying isActive value, it is saving the object with isActive set to false even though I have set the default to True. What could be the issue here?

EDIT:

<form method="POST" action="{% url 'trans:createmode' %}" class="modal-content form-horizontal" id="creator">
  {% csrf_token %} {{ form }}
  <label for="mode" class="col-sm-3 control-label">Transport Mode</label>
  <input type="text" name="typeName" maxlength="200" class="form-control" required="required" id="typeName">
  <input type="submit" class="btn btn-fill btn-success pull-right" id="submit" value="Save">
</form>
like image 701
want2learncsharp Avatar asked Jan 31 '26 05:01

want2learncsharp


1 Answers

I assume you are using a ModelForm for TransType model. blank=True says that the field can be empty in the form, is not required.

If the isActive will be empty in the form, value will be ' ' and will be treat as False by the BooleanField, test in django shell:

from django.forms.fields import BooleanField
field = BooleanField()
field.to_python('')  # Results False
field.to_python('Test')  # Results True
field.to_python(True)  # Results True

Suggestion: You can add initial=True in the form field, or remove blank=True from the Model fields, so that in the form the field will be required.

like image 63
sergiuz Avatar answered Feb 01 '26 19:02

sergiuz