Skip to content Skip to sidebar Skip to footer

Django 1.6, How To Set Field Default Value For Createview

models.py class App(models.Model): name = models.CharField(max_length=10, default='') desc = models.CharField(max_length=10, default='') views.py class AppCreate(CreateVi

Solution 1:

Default value actually rectifies the need for the optional field. If you do not enter any value, you dont get an error, but the default value is stored, which is of course an empty string(value). To specify optional explicitly, use blank=True

desc = models.CharField(max_length=10, blank=True)

can be used

Solution 2:

When you set a default for a model field in Django, it isn't included in the SQL schema generated by Django.

As long as you create your model instances using the ORM, then this doesn't matter, as Django will set the default value. However, if you create model instances using raw SQL, then you do need to make sure you use the default value for the field if required.

There is a ticket 470 for adding default values to the SQL schema, but it has been closed as won't fix. Remember than default can be a callable as well as a constant, so it wouldn't be possible to add some callables as defaults to the SQL schema.

If you really require the default to be added to the SQL schema, you could run the alter table statement manually, or add it to a migration.

To answer your second question, use blank=True if a CharField is optional.

Post a Comment for "Django 1.6, How To Set Field Default Value For Createview"