16

I have the following code in my admin.py:

class UserManagedGroupAdmin(admin.ModelAdmin):
    inlines = [MembershipInline]
    search_fields = ('name', 'leader__username', )
    list_display = ('__unicode__', 'leader', )
    filter_horizontal = ('permissions', )
    raw_id_fields = ('leader', )

admin.site.register(UserManagedGroup, UserManagedGroupAdmin)

The magnifying glass icon for searching doesn't appear in the admin page.

This is what I'm getting:

enter image description here

As you can see it's showing the unicode method of the model instead of the search icon I want.

Field 'leader' is a ForeignKey to User.

Could it be that django disables the search for ForeignKeys to User for security reasons, or am I doing something wrong?

The widget would be perfect for choosing users... I mean, I can't leave a huge select there with every user of my site.

Thanks.

Adrián
  • 6,135
  • 1
  • 27
  • 49

3 Answers3

35

I've found the problem thanks to this message in django-users.

I had to register in the admin the model to which the ForeignKey points to.

The search doesn't work without that.

Adrián
  • 6,135
  • 1
  • 27
  • 49
  • 6
    Thanks, this worked for me. Just to clarify for the example given in the question. The asker doesn't have `User` registered in the admin so the admin doesn't recognize it. The manifestation of that is that the spyglass icon doesn't show. – Tim Fletcher Apr 14 '15 at 14:14
2

In the admin.py file add:

admin.site.register(YourModel)

This did the trick, Where YourModel is the model to be displayed with the magnifying glass

elad silver
  • 9,222
  • 4
  • 43
  • 67
2

Hi encounter the same issue but reason's a bit different.

To integrate the User and UserGroup with another app's admin (e.g. some_app)

I added below code to some_app/admin.py

class ProxyUser(User):
    class Meta:
        proxy = True
        verbose_name = User._meta.verbose_name
        verbose_name_plural = User._meta.verbose_name_plural


class ProxyGroup(Group):
    class Meta:
        proxy = True
        verbose_name = Group._meta.verbose_name
        verbose_name_plural = Group._meta.verbose_name_plural

admin.site.unregister(Group)
admin.site.unregister(User)
admin.site.register(ProxyGroup)
admin.site.register(ProxyUser, UserAdmin)

I think the unregister(...) will affect the other app's admin Globally!

That's another cause of missing search icon.

C.K.
  • 4,348
  • 29
  • 43
  • If I'm in this situation, but I want the chooser to appear for me still? Because I do register an Admin which is a combined Admin for the Django `User` class plus my customized `UserProfile` class. – Csaba Toth Dec 10 '19 at 21:18
  • I gonna register a separate Admin for the `UserProfile` and will try to hide it. – Csaba Toth Dec 10 '19 at 21:35
  • https://stackoverflow.com/questions/2431727/django-admin-hide-a-model – Csaba Toth Dec 10 '19 at 21:44