Python 第一次保存对象时,使 django 模型字段只读或在管理员中禁用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28275239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
make django model field read only or disable in admin while saving the object first time
提问by Gaurav
I want to disable the few fields from model in django admin while saving initially.
我想在最初保存时禁用 django admin 模型中的几个字段。
"<input type="text" id="disabledTextInput" class="form-control" placeholder="Disabled input">"
like this.
像这样。
My model is:
我的模型是:
class Blogmodel(models.Model):
tag = models.ForeignKey(Tag)
headline = models.CharField(max_length=255)
image=models.ImageField(upload_to=get_photo_storage_path, null=True, blank=False)
body_text = models.TextField()
pub_date = models.DateField()
authors = models.ForeignKey(Author)
n_comments = models.IntegerField()
i want to disable the "headline" and "n_comments". i tried it in admin.py file, but its not disabling the fields on initial saving. But for editing the fields its working, it making the fields read only.
我想禁用“标题”和“n_comments”。我在 admin.py 文件中尝试过,但它没有在初始保存时禁用这些字段。但是为了编辑其工作的字段,它使字段只读。
in admin.py
在 admin.py
class ItemAdmin(admin.ModelAdmin):
exclude=("headline ",)
def get_readonly_fields(self, request, obj=None):
if obj:
return ['headline']
else:
return []
Headling getting disabled but for edit only. i want to disable it at the time of object creation. i.e. first save. can anyone guide me for this?
标题被禁用但仅供编辑。我想在创建对象时禁用它。即先保存。任何人都可以指导我吗?
采纳答案by Bernhard Vallant
If you want to make the field read-only during creation you should do it the other way round:
如果您想在创建期间将该字段设为只读,您应该反过来做:
def get_readonly_fields(self, request, obj=None):
if obj is None:
return ['headline']
return []
回答by Gaurav
For making it disabled while saving initial object and for editing also we can do this
为了在保存初始对象和编辑时禁用它,我们也可以这样做
class ItemAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
if obj is None:
return ['headline']
else:
return ['headline']
return []
it worked for me.
它对我有用。
回答by GwynBleidD
There is no need to override get_readonly_fields
. Simplest solution would be:
无需覆盖get_readonly_fields
. 最简单的解决方案是:
class ItemAdmin(admin.ModelAdmin):
exclude=("headline ",)
readonly_fields=('headline', )
When using readonly_fields
you can't override get_readonly_fields
, because default implementation reads readonly_fields variable. So overriding it only if you have to have some logic on deciding which field should be read-only at time.
使用readonly_fields
时不能覆盖get_readonly_fields
,因为默认实现读取 readonly_fields 变量。所以只有当你必须有一些逻辑来决定哪个字段应该是只读的时候才覆盖它。