[Django]-Admin site uses default database in Django 1.6

0πŸ‘

βœ…

I have finally found a way to force Django admin to use the database I want, but it’s really hacky. If someone comes with a better solution, please do post it.

I have created a file named admin_helper.py where I redefine the methods that use the @transaction.atomic decorator in Django codebase, with exactly the same content, and using the decorator @transaction.atomic(DATABASE_ALIAS) which tells Django to use the correct database:

DATABASE_ALIAS = 'alias_of_the_database_i_want_to_use'

class ModelAdminCustom(admin.ModelAdmin):
    @csrf_protect_m
    @transaction.atomic(DATABASE_ALIAS)
    def add_view(self, request, form_url='', extra_context=None):
        # exact same content as the method defined in django.contrib.admin.options.ModelAdmin

    @csrf_protect_m
    @transaction.atomic(DATABASE_ALIAS)
    def change_view(self, request, object_id, form_url='', extra_context=None):
        # exact same content as the method defined in django.contrib.admin.options.ModelAdmin

    @csrf_protect_m
    @transaction.atomic(DATABASE_ALIAS)
    def delete_view(self, request, object_id, extra_context=None):
        # exact same content as the method defined in django.contrib.admin.options.ModelAdmin

class MultiDBUserAdmin(UserAdmin):
    @sensitive_post_parameters_m
    @csrf_protect_m
    @transaction.atomic(DATABASE_ALIAS)
    def add_view(self, request, form_url='', extra_context=None):
        # exact same content as the method defined in django.contrib.auth.admin.UserAdmin

# Unregister existing instance of UserAdmin for the User model, and register my own
try:
    admin.site.unregister(User)
finally:
    admin.site.register(User, MultiDBUserAdmin)

Then in my normal admin.py:

from myapp.admin_helper import ModelAdminCustom

class MyModelAdmin(ModelAdminCustom):
    pass

admin.site.register(MyModel, MyModelAdmin)
πŸ‘€Thierry J.

Leave a comment