Home > Blockchain >  django admin - when adding a model, restrict foreignkey that belong to current user
django admin - when adding a model, restrict foreignkey that belong to current user

Time:09-03

I have two models in my app. Each model has a foreignkey to the user and the two models are also related through a foreignkey. I want to use the django admin to add new objects for a model. The add_view page gives me a drop down to pick the foreignkey field, but I want to restrict these choices to the current user.

models.py

class Notebook(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    name = models.CharField(max_length=20)

class Post(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    entry = models.CharField(max_length=500)
    notebook = models.ForeignKey(Notebook, on_delete=models.CASCADE)

So when I am in the admin and click to add a new post, I want to choose from notebooks that only belong to me. I see all the notebooks in the dropdown (I am logged in as admin with superuser permissions).

CodePudding user response:

You can define limit_choices_to in ModelAdmin:

class MyModelAdmin(ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'user':
            kwargs['limit_choices_to'] = {'user': request.user}
        return super().formfield_for_foreignkey(db_field, request, **kwargs)
  • Related