Skip to main content

How to expose your multiple database for admin site in django

Assuming you have multiple databases in your django project for different apps. Now you realize that when you save or do other operations in admin site for your app model , you realize that values are save to default database from project.

Below we will see simple steps to make admin site of django to use your other database configured for the app instead of default.

Now your multiple database in settings.py may looks something like this

settings.py


So inorder to inform the django admin site use your intendended database for your app.

Navigate to your app in the django project and open your admin.py. Below example shows model names ProfileSection which when the user saves the information in admin site uses default database.

admin.py


If you want to provide an admin interface for a model on a database other than that specified by your router chain, you’ll need to write custom ModelAdmin classes that will direct the admin to use a specific database for content. 

You can now create a ModelAdmin object in your admin.py like below. Also mention which database to be used in the "using" keyword

ModelAdmin object in admin.py


Once you have created your custom ModelAdmin setup . You can now proceed to register your model in admin site to use your other database. In my case "resumeapp" will be used.


Registering model in admin .py



You are all set . Now when you save or do other operation in admin site on your model in the app , Django will use database mentioned in "using" keyword.

Hope this was helpful.!!

Comments

Popular posts from this blog

How to resolve Forbidden(403) if Djangos CSRF mechanism has not been used in POST method

Are you a newbie to Django like me. ? if yes , you would have come across "Forbidden (403)" when you are using forms or when you have used ajax post method to your app view and have not used CSRF mechanism properly. Below are ways I have resolved the 403 issue. Even before we see how CSRF should be used , we will see what CSRF is actually for. Cross Site Request Forgery protection " The CSRF middleware and template tag provides easy-to-use protection against Cross Site Request Forgeries. This type of attack occurs when a malicious website contains a link, a form button or some JavaScript that is intended to perform some action on your website, using the credentials of a logged-in user who visits the malicious site in their browser. A related type of attack, ‘login CSRF’, where an attacking site tricks a user’s browser into logging into a site with someone else’s credentials, is also covered."  Please see:   https://docs.djangoproject.com/en/3.0/ref/csrf/#module-djan...