简体   繁体   中英

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

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).

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM