Default value for field in Django model

PythonDjangoDjango ModelsDjango Admin

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

Solution 3 - Python

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'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYuval AdamView Question on Stackoverflow
Solution 1 - PythonFogleBirdView Answer on Stackoverflow
Solution 2 - PythonAndrew HareView Answer on Stackoverflow
Solution 3 - PythonMrOodlesView Answer on Stackoverflow