Sunday, September 21, 2014

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

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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/12321833-cdf7-4df7-bfa8-25502d3a27ce%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment