Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin List Display + ForeignKey = Empty Change List

I've got a weird problem in django admin list_display. Whenever I add a foreign key to a list_display the whole change list view goes blank showing only the total no of entries.

models.py:

class Organization(models.Model):
    org_id = models.AutoField(primary_key=True)
    org_name = models.CharField(max_length=288)

    def __unicode__(self):
        return self.org_name

    class Meta:
        db_table = u'organization'

class Server(models.Model):
    server_id = models.AutoField(primary_key=True)
    server_name = models.CharField(max_length=135,verbose_name="Server Name")
    org = models.ForeignKey(Organization,verbose_name="Organization")   

    def __unicode__(self):
        return self.server_name

    class Meta:
        db_table = u'server'

admin.py:

class ServerAdmin(admin.ModelAdmin):
    list_display = ('server_name','org') 
admin.site.register(Server,ServerAdmin) 

Now I'd expect this code to show me the organization name in the ChangeList View, But instead I get this:

empty changelist :(

If I remove the org in the list_display of ServerAdmin class, I get this:

change list with data :(

I didn't modify the template or override any ModelAdmin methods. I'm using Mysql(5.1.58) as my database that comes with ubuntu 11.10 repository.

I'll be really glad if I could a get a sloution for this problem guys. Thanks in advance.

like image 956
Pannu Avatar asked Jan 20 '12 13:01

Pannu


1 Answers

I second Stefano on the fact that null=True, blank=True is to be added. But, I think you only need to add it to the org_name field of the Organization model. That should make your way through. It has to be done because you have run inspectdb to create models from your legacy DB. And probably the organization table in the DB has an empty string stored. So, adding the above would allow the Admin to have a blank field/column displayed.

Moreover, you can also try using callbacks in situations where you don't want to make changes to your model definition like the above.

like image 56
Sandip Agarwal Avatar answered Sep 23 '22 14:09

Sandip Agarwal