简体   繁体   中英

Django admin filtering users

I have an app which is like a store where each store has many products and a product has many orders ( product_id , user_id ). On the products page I show the number of users that own that product and I want to place a link that will redirect me to the list for those users.

I create the link as follows:

def users_link( self, product ):
    url = urlresolvers.reverse( 'admin:auth_user_changelist' )
    return u'<a href="%s?orders__product_id=%d">%s</a>' %( url, product.pk, product.users_count )

But I get the following error:

DisallowedModelAdminLookup at /admin/auth/user/
Filtering by orders__product_id__exact not allowed

Even if I add orders__product_id to the list of allowed list_filter for users it still denies me. I can see the filter on the users page but when I click on it it just errors out. How can I achieve this?

My guess is you don't register this filter with the UserAdmin model. To add a filter to the Users section in the admin panel you could add it to existing UserAdmin model in the admin.py file of your app:

from django.contrib.auth.admin import UserAdmin

then add the filter you want

UserAdmin.list_filter += ('orders__product_id',)

You should see now in the User section of the admin panel, in the right sidebar, a new filter. If the filter is incorrect you should see the error in the shell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM