Default value for field in Django model


Suppose I have a model:

class SomeModel(models.Model):
    id = models.AutoField(primary_key=True)
    a = models.CharField(max_length=10)
    b = models.CharField(max_length=7)

Currently I am using the default admin to create/edit objects of this type. How do I remove the field b from the admin so that each object cannot be created with a value, and rather will receive a default value of 0000000?

10/12/2012 1:52:17 PM

Accepted Answer

Set editable to False and default to your default value.

b = models.CharField(max_length=7, default='0000000', editable=False)

Also, your id field is unnecessary. Django will add it automatically.

4/16/2009 12:16:41 PM

You can set the default like this:

b = models.CharField(max_length=7,default="foobar")

and then you can hide the field with your model's Admin class like this:

class SomeModelAdmin(admin.ModelAdmin):
    exclude = ("b")

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow