CNB
CNB

Reputation: 37

Searching by Username field in Django admin

I would like to know how to search using the details in the username column of my Django admin without directly knowing the username.

I have objects in my admin and I want to be able to seach by the USERNAME_FIELD to access these objects about a given user.

At first I tried:

 search_fields = ('user__username', 'user__email',)

But that gave a FieldError: Cannot resolve keyword 'username' into field.

I'm now trying something I found in the Django documentation but it's giving me an error which says 'too many values to unpack'.

def get_search_results(self, request, queryset, search_term):
     queryset, use_distinct = super(MyAdmin, self).get_search_results(request, queryset, search_term)
     queryset = self.model.objects.filter(get_user_model().USERNAME_FIELD)
     return queryset, use_distinct

The only solution I can think of is formatting a string which I'd rather not do since it's not very good code.

Upvotes: 2

Views: 2390

Answers (1)

Muhammad Hassan
Muhammad Hassan

Reputation: 14391

You can do this by adding following in your admin.py file.

class WebUser(User):

    class Meta:
        proxy = True
        verbose_name = "User"
        verbose_name_plural = "Users"


class UserAdmin(admin.ModelAdmin):
    search_fields = ('user__username', 'user__email')

admin.site.register(WebUser, UserAdmin)

Hope this will help.

Upvotes: 2

Related Questions