Yuval Adam
Yuval Adam

Reputation: 165340

How can I set a default value for a field in a 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 Django admin to create/edit objects of this type. How do I remove the field b from the Django admin so that each object cannot be created with a value, and rather will receive a default value of 0000000?

Upvotes: 134

Views: 272786

Answers (3)

FogleBird
FogleBird

Reputation: 76852

Set editable to False and default to your default value.

http://docs.djangoproject.com/en/stable/ref/models/fields/#editable

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

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

Upvotes: 201

MrOodles
MrOodles

Reputation: 1868

You can also use a callable in the default field, such as:

b = models.CharField(max_length=7, default=foo)

And then define the callable:

def foo():
    return 'bar'

Upvotes: 29

Andrew Hare
Andrew Hare

Reputation: 351698

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")

Upvotes: 27

Related Questions