Solution : filtering listbox per user in 'admin add' form

16 views
Skip to first unread message

Salvatore DI DIO

unread,
Sep 21, 2014, 3:54:49 PM9/21/14
to django...@googlegroups.com
This post follows my previous on filtering a listbox in 'admin add form'
per user

This is ceratinly a hack but It works for now,
If you have a better solution, I would be glad to read it.

In order to access the request object in '/contrib/admin/helpers.py'
I modified the '/contrib/admin/views/main.py'

def get_queryset(self, request):
    from django.conf import settings
    settings.CONNECTED_USER =  str(request.user)


And in '/contrib/admin/helpers.py' I can get the CONNECTED_USER
and so could filter my list in the 'add' form

from portfolio.models import Album
from portfolio.models import User
from django.conf import settings

class AdminField(object):
    def __init__(self, form, field, is_first):
        self.field = form[field]  # A django.forms.BoundField instance
        self.is_first = is_first  # Whether this field is first on the line
        self.is_checkbox = isinstance(self.field.field.widget, forms.CheckboxInput)
        if (field == 'albums'):
            self.restrictAlbumQuery()

    def restrictAlbumQuery(self):
        # defined in main.py
        currentUser = settings.CONNECTED_USER
        qs =  Album.objects.filter(user = User.objects.get(username=currentUser))  #here I can filter the albums listbx
        self.field.field.queryset = qs

Reply all
Reply to author
Forward
0 new messages