Reputation: 67
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>
Upvotes: 3
Views: 1383
Reputation: 456
default argument is not valid for BooleanField in some versions of Django, so to create BooleanField with default=True if input is nothing, you can use this code:
class MyForms(forms.Form):
bool_field = forms.NullBooleanField(required=False)
def clean_bool_field(self, default=True):
value = self.cleaned_data.get("bool_field")
return default if bool_field is None else use bool_field
Upvotes: 0
Reputation: 5529
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.
Upvotes: 1
Reputation: 3483
HI can you try like this
model.py
class TransType(models.Model):
typeName = models.CharField(max_length=200)
isActive = models.BooleanField(default=True)
def __str__(self):
return self.typeName
Just remove blank=True, i think it must be working.
just go to django shell and do like
object = TransType()
object. typeName = 'test'
object.save()
it must be working
Upvotes: 0