limit the foreign key select in admin

9 views
Skip to first unread message

Ottavio Campana

unread,
Sep 23, 2008, 7:41:45 AM9/23/08
to Django users
Hi, I just started studying django and I'm having a problem with its
admin interface. In my model I have two classes, let's say

class ClassA (models.Model):
user = models.ForeignKey(User, help_text=_('ClassA owner'))
...

class ClassB (models.Model):
classa = models.ForeignKey(ClassA)
....

Now I'm trying to give the possibility of editing to each user his
instances of ClassB, even though only the superuser will create ClassA
objects. To achieve this, I had to overwrite queryset in the
modelAdmin of ClassB and it works.

The problem that now I'm having is that if a user modifies a ClassB
object he will see in the admin a select for all possible ClassA
objects, not only those owned by him. I tried to overwrite queryset in
the modelAdmin of ClassA, but is doesn't work.

I think that the admin is calling another function, and I'm not able
to understand which one it is.

Do you have a hint?

Ottavio Campana

unread,
Sep 23, 2008, 11:33:15 AM9/23/08
to Django users
after several tests, I found a working solution, but I don't know if
it is correct. I overwrote the following function in ClassBAdmin

def render_change_form(self, request, context, add=False,
change=False, form_url='', obj=None):
if not request.user.is_superuser:
adminform = context.__getitem__('adminform')
qs = context['adminform'].form['classa'].field.queryset
qs = qs.filter (user=request.user)
context['adminform'].form['classa'].field.queryset = qs
return super(ClassBAdmin, self).render_change_form(request,
context, add, change, form_url, obj)

Is there any better solution?
Reply all
Reply to author
Forward
0 new messages