I'm trying to filter the User list in Django using a UserProfile Field... I need to implement a queue system where new users are put in a queue until an Admin approves them.
I simply added a is_in_queue
boolean field to my UserProfile model... However, when displaying the user list in my Admin area, I realized that you can't filter the list using a Model's foreign key field (in this case, a field of UserProfile)
Apparently, list_display
items can be callables but list_filter
can't, so I can list IF a user is in the queue without a problem, but the admin would have to scroll through the whole user list to spot which ones are in the queue which makes no sense... Filtering only users that are in the queue (using userprofile.in_queue) would be much more practical...
Finally, I thought about adding a custom view to my admin area that would list only the user in the queue, but that custom view does not show up on the Admin area Index page, and putting together a whole new AdminSite only for a new filtering option seems a bit over the top...
So basically to sum it up: Can I filter my User list based on a UserProfile field? If not, can I add a custom view that's accessible from the front page without having to create a completely new AdminSite only for that?
Django 1.3 fixed that - list_filter now allows to span relations:
https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter
You may want to take a look in to using a custom manager for the admin_objects
of your model.
class UserAdminManager(models.AdminManager):
"""
Custom manager for the User model.
"""
def get_query_set(self):
"""
Overwrites the get_query_set to only return Users in the queue.
"""
return super(UserAdminManager, self).get_query_set().filter(userprofile__queue=True)
By overwriting the get_query_set
method you can filter the results. Then just assign this to the admin_objects
property of your User
model.
admin_objects = UserAdminManager()
Some of the property names in my example may be wrong, as I don't know your model setup, but hopefully you get the idea.
You can research this further by checking out the django docs and searching for "custom managers".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With