-->

Django 1.6, how to set field default value for Cre

2019-07-31 09:54发布

问题:

models.py

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

views.py

class AppCreate(CreateView):
    template_name = "app/add.html"
    model = App 

templates

<!DOCTYPE html>
<html lang="en">
<head>   
    <meta charset="UTF-8">
    <title></title>
</head>  
<body>   
    <form action="" method="POST">
    {% csrf_token %}                                                         
    {{form}}
    <input type="submit" value='submit'>
    </form>
</body>  
</html>  

Here two problems:

  1. Why I set model field default value, but it doesn't work in database? I check sql statement, no default value set

  2. If want to set desc as an optional field (desc field in html is not mandatory), what shoud I do?

回答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



回答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.