Django admin:使字段在添加中可编辑但不可编辑 [英] Django admin: make field editable in add but not edit
本文介绍了Django admin:使字段在添加中可编辑但不可编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似的模型:
class Product(models.Model):
third_party_id = models.CharField(max_length=64, blank=False, unique=True)
使用 Django 默认主键.我希望用户能够通过在添加页面上设置 third_party_id 来添加产品,但我不希望该字段在编辑页面中可编辑以避免损坏 third_party_id.在 Django 文档中,相同的设置似乎用于添加和编辑.这可能吗?
that uses the Django default primary key. I want users to be able to add products by setting the third_party_id on the add page, but I don't want that field editable in the edit page to avoid corrupting the third_party_id. In the Django docs, the same settings appear to be used for add and edit. Is this possible?
推荐答案
不要设置 self.readonly_fields
以避免线程问题.而是覆盖 get_readonly_fields 方法:
Do not set self.readonly_fields
to avoid thread issues. Instead override get_readonly_fields method:
def get_readonly_fields(self, request, obj=None):
if obj: # obj is not None, so this is an edit
return ['third_party_id',] # Return a list or tuple of readonly fields' names
else: # This is an addition
return []
这篇关于Django admin:使字段在添加中可编辑但不可编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文