Django List Manager + ForeignKey = empty change list

I have a strange problem in django admin list_display . Whenever I add a foreign key to list_display , the entire list of change lists becomes empty, showing only the total number 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 expect this code to show me the name of the organization in ChangeList View , but instead I get the following:

empty changelist :(

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

change list with data :(

I did not modify the template or redefine any ModelAdmin methods. I use Mysql (5.1.58) as my database, which comes with the ubuntu 11.10 repository.

I will be very happy if I can get an answer to this problem. Thanks in advance.

+6
source share
4 answers

I second Stefano regarding the fact that null=True, blank=True should be added. But it seems to me that you need to add it to the org_name field of the Organization model. This should pass. This needs to be done because you ran inspectdb to create models from your old database. And, probably, the Organization table in the database stores an empty row. Thus, adding the above will allow the administrator to display an empty field / column.

In addition, you can also use callbacks in situations where you do not want to make changes to the model definition, as described above.

+7
source

Try adding null=True, blank=True to all fields of your model.

Normally, the django admin will shut down (until it displays entries in the list) if the line does not check the model constraints.

+2
source

See: fooobar.com/questions/34392 / ...

Will the following work for you?

admin.py:

 class ServerAdmin(admin.ModelAdmin): list_display = ('server_name','org__org_name') admin.site.register(Server,ServerAdmin) 
+1
source

I had a similar problem and decided to do it (using your example):

 class ServerAdmin(admin.ModelAdmin): list_display = ('server_name', 'get_org') def get_org(self, obj): return obj.org.org_name get_org.short_description = 'Org' admin.site.register(Server,ServerAdmin) 
0
source

Source: https://habr.com/ru/post/906479/


All Articles