oct
2008
Filter the Django ModelAdmin set
I was playing around today and thought it would be quite cool to modify/filter the query for the ModelAdmin class. Aiming to create helper functionality rather than a security feature. After all django-admin users are (or at least, should be) trusted users.
Either way, it can be handy to filter down the options and clear things up a bit.
When you make the ModelAdmin class in admin.py you can then override the default queryset method. So say for example you have a set of articles and you only want users to be able to edit articles they have originally posted.
So a VERY simple model could look like this;
class Article(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=60) content = models.TextField()
Then in admin.py;
class ArticleAdmin(admin.ModelAdmin): def queryset(self, request): if request.user.is_superuser: qs = self.model._default_manager.get_query_set() else: qs = self.model._default_manager.get_query_set().filter(author = request.user) ordering = self.ordering or () if ordering: qs = qs.order_by(*ordering) return qs
And there you have it. Now in the admin the user will only see posts that they are the author of (unless the user is a super_user). Again just to stress this doesn't enforce security (you can get to the other posts to edit by modifying the page address) but its still quite handy to be able to do.
You may have use cases where you only want the 10 more recent posts to be edited or you might want to 'lock' a post after its finished and when its not on the list people wont edit it... And so on. One thing I guess it does help avoid slip of the finger accidental changes that we sometimes all do!