I want Django's administration site (admin) to display foreign keys filtered by the user.

Asked 2 years ago, Updated 2 years ago, 75 views

I use admin function in Django 1.6.
I would like to see the foreign key of the model filtered.

Model is

class Hoge (models.Model):
    user=models.ForeignKey(User, unique=False, verbose_name=u'user')

and

class Bar (models.Model):
    user=models.ForeignKey(User, unique=False, verbose_name=u'user')
    questions = models.ForeignKey (Hoge)


when there are two Hoge and Bar models, as shown in .

at admin.py
classBarAdmin(admin.ModelAdmin):
    # approximately

shows the bar.


When editing the bar in admin, click
admin Filter
It looks like this, but I want to filter it.

I think I can do it just in case.

classBarAdmin(admin.ModelAdmin):
    form = BarForm

and BarForm

class BarForm (forms.ModelForm):
    def__init__(self, *args, **kwargs):
        # I can't do it for some reason...
        self.request=kwargs.pop("request")
        # approximately

However, since kwargs does not have a request key,
Unable to retrieve the user you are currently accessing.

Please let me know.

python django

2022-09-29 21:49

1 Answers

If I want to filter the questions field of Bar with request.user, will it be as I wrote?

classBarAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "questions":
            kwargs ["queryset"] = Hoge.objects.filter(user=request.user)
        return super(BarAdmin,self).formfield_for_foreignkey(db_field,request,**kwargs)

https://docs.djangoproject.com/en/1.8/ref/contrib/admin/ #django.contrib.admin.ModelAdmin.formfield_for_foreignkey


2022-09-29 21:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.