Django 管理中的小部件
我需要一个可以使外键只读的小部件,并且它应该显示与该字段相关的值,而不是 id
假设
Class A(models.Model):
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=200)
def __unicode__(self):
return self.name
Class B(models.Model):
id=models.AutoField(primary_key=True)
name=models.ForeignKey(A)
description=models.CharField(max_length=200)
现在当我将 B 类的“名称”设置为只读时,然后在管理中它只显示 id 对应的值A 类中该名称的名称。是否有任何小部件可以使该字段为只读并且还显示值而不是 id
I need a widget which can make a foreignkey readonly and also it should display the value related to that field not the id
suppose
Class A(models.Model):
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=200)
def __unicode__(self):
return self.name
Class B(models.Model):
id=models.AutoField(primary_key=True)
name=models.ForeignKey(A)
description=models.CharField(max_length=200)
now when i make 'name' of class B as readonly then in admin it only displays the id corresponding value of that name in Class A.Is there any widget that can make the field as readonly and also display the value not id
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
作为解决方法,您可以:
1) 将字段
name
添加到 ModelAdmin 的raw_id_fields
属性,然后2) 使用 javascript 禁用 id 输入框(保留值标签不变)。
除了安全问题(如果有人模仿禁用/删除的输入框)之外,它会执行您所询问的操作。这还可以在从
ModelForm
继承的类的clean_name
函数中进行处理。As a workaround you can:
1) Add the field
name
toraw_id_fields
attribute of ModelAdmin and then2) Disable id input box using javascript (leaving intact the value label).
It will do what you're asking about except for security issue (if someone imitates disabled/deleted input box). That can additionally be dealt with for example in
clean_name
function of a class inherited fromModelForm
.如果我在 help_text 中显示值会怎样。意味着我在 help_text 中显示值以及 Id
这可以简单地实现
What if i display the value in the help_text.Means I m showing the value in help_text as well as Id
This can be achievd simply
第三种解决方法是使用 Django trunk,它添加 readonly_fields 属性。
另一种选择是使用以下补丁修补当前版本的 django: http://code.djangoproject.com/ Ticket/342
编辑:我正在使用 django r12204,因为后来的修订破坏了 django-cms 应用程序,这对我来说至关重要。我认为 django 的后续版本有这个,但我必须修补我的 django 安装以显示外键值而不是 id。但似乎这种行为在 django 主干中仍然存在,所以这里是补丁: http://dpaste.com /保持/147814/
The third workaround is to use Django trunk which adds readonly_fields property to ModelAdmin.
Other alternative is to patch your current version of django with this patch: http://code.djangoproject.com/ticket/342
EDIT: I am using django r12204, because later revisions break django-cms application, which is vital for me. I thought that later revisions of django had this, but I had to patch my django installation to show foreign key values not id's. But it seems that this behaviour still persists in django trunk, so here is the patch: http://dpaste.com/hold/147814/