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
?
目前,我正在使用默认的admin来创建/编辑此类对象。如何从admin中删除字段b,以便不能使用值创建每个对象,而是接收到默认值0000000?
3 个解决方案
#1
106
Set editable
to False
and default
to your default value.
将editable设置为False,并将其设置为默认值。
http://docs.djangoproject.com/en/dev/ref/models/fields/#editable
http://docs.djangoproject.com/en/dev/ref/models/fields/编辑
b = models.CharField(max_length=7, default='0000000', editable=False)
Also, your id
field is unnecessary. Django will add it automatically.
而且,您的id字段是不必要的。Django将自动添加它。
#2
20
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")
#3
15
You can also use a callable in the default field, such as:
您还可以在默认字段中使用callable,例如:
b = models.CharField(max_length=7, default=foo)
And then define the callable:
然后定义可调用的:
def foo():
return 'bar'
#1
106
Set editable
to False
and default
to your default value.
将editable设置为False,并将其设置为默认值。
http://docs.djangoproject.com/en/dev/ref/models/fields/#editable
http://docs.djangoproject.com/en/dev/ref/models/fields/编辑
b = models.CharField(max_length=7, default='0000000', editable=False)
Also, your id
field is unnecessary. Django will add it automatically.
而且,您的id字段是不必要的。Django将自动添加它。
#2
20
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")
#3
15
You can also use a callable in the default field, such as:
您还可以在默认字段中使用callable,例如:
b = models.CharField(max_length=7, default=foo)
And then define the callable:
然后定义可调用的:
def foo():
return 'bar'