Home > database >  How do I make ManyToManyField limit_choices_to equal to request.user (Django)?
How do I make ManyToManyField limit_choices_to equal to request.user (Django)?

Time:01-11

I should limit choices of manytomanyfield to logged in admin user profile, in django admin.

class News(models.Model):
    title=models.CharField(max_length=200)
   users=models.ManyToManyField(User, blank=True, limit_choices_to={"profile__school":      "request.user.profile.school"})

I have tried to implement it in admin.ModelAdmin, where I can access request.user, but couldn't find a way to do it.

CodePudding user response:

You don't do this in the model layer. Django's user layer is request unaware. Some code paths don't even have a request, for example if these are done through a Python script, or a Django management command.

You can limit the choices in the ModelAdmin by overriding get_form:

class NewsAdmin(ModelAdmin):
    def get_form(self, request, obj=None, change=False, **kwargs):
        form = super().get_form(request, obj=obj, change=change, **kwargs)
        form.base_fields['users'].queryset = User.objects.filter(
            profile__school__profile__user=request.user
        )
        return form

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

  • Related