开发者

widgets in django admin

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.C开发者_如何学PythonharField(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


As a workaround you can:

1) Add the field name to raw_id_fields attribute of ModelAdmin and then

2) 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 from ModelForm.


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

def get_form(self, request, obj=None):
    form = super(BAdmin,self).get_form(request, obj)
    link = obj.id
    pl=A.objects.get(id=obj.name_id)
    help_text1 = "%s"%(pl.name)
    form.base_fields['name'].help_text = help_text1
    return form


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜