[Answer]-How to override django admin form Foreignkey based on request.user

1👍

You cannot initiate the store field with request.user in the field declaration. You can try the following:

class MyAwesomeForm(forms.ModelForm):
    store = forms.ModelChoiceField(Store.objects)
    class Meta:
       model = Promo

def __init__(self, user, *args, **kwargs):
    super(MyAwesomeForm, self).__init__(*args, **kwargs)
    self.fields['store'].queryset = Store.objects.filter(owner=user)

While instantiating the form you can pass the request.user object.

myform = MyAwesomeForm(request.user)

If you want to achieve this in the admin you might try this
For providing only the objects related to the logged-in user in the admin provides the possibility to overwrite ModelAdmin.queryset function:

class MyModelAdmin(admin.ModelAdmin):
    form = MyAwesomeAdminForm()
    def queryset(self, request):
        qs = super(MyModelAdmin, self).queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(store__owner=request.user)

class MyAwesomeAdminForm(forms.ModelForm):
    class Meta:
       model = Promo

Note that store__owner only works if you have a foreign key field stored in your promo model as such:

class Promo(models.Model):
    store = models.ForeignKey(Store)

class Store(models.Model):
    owner = models.ForeignKey(User)

I assume it should also be possible to somehow pass the request to the init method of the form. But did not find a suitable approach to do it.

Leave a comment