[Answered ]-Django admin show only current user for User field as ForeignKey while creating and object

1πŸ‘

βœ…

I would advise to simply exclude the field from the form, and assign the user when you save the model with the .save_model(…) methodΒ [Django-doc]:

class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'slug', 'status', 'created_on')
    list_filter = ('status',)
    search_fields = ['title', 'content']
    prepopulated_fields = {'slug': ('title',)}
    exclude = ('author',)

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if not request.user.is_superuser:
            qs = qs.filter(author=request.user)
        return qs

    def save_model(self, request, obj, form, change):
        obj.author = request.user
        return super().save_model(request, obj, form, change)

0πŸ‘

Try formfield_for_foreignkey()

It overrides the default formfield for a foreign keys field. In your case, to return only current user for author foreign key field:

class PostAdmin(admin.ModelAdmin):
    ...

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'author':
            kwargs['queryset'] = User.objects.filter(id=request.user.id)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

Leave a comment