views:

168

answers:

3

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

A: 

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.

Antony Hatchkins
I dont want to use javascript
ha22109
A: 

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
ha22109
A: 

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/

fest
if i use readonly_field in model Admin then also it will show the Id not the value.
ha22109
I had the same problem. I ended up hacking django admin's code to show the object's value for foreignkeys- here is my diff: http://dpaste.com/hold/147814/
fest
can describe little more.I m not able to know that where to copy that code
ha22109