6

How do I test a database connection for Django? For example to make sure that the username and password of the database is correct.

Or if it is easier, where do I "catch" the database error when database connection fails ?

I have a scenario where database connection parameters is defined in a form by user. I need to make sure the username/password is correct and database must connect successfully before proceeding.

I can't seem to find any documentation anywhere, as most articles assume that the database connection is always successful.

Thanks in advance.

Renyi
  • 183
  • 1
  • 9

1 Answers1

4

Write a middleware ("How Django processes a request") which will check for the database connection and redirect to your edit form.

class DbCheckMiddleware(object):

    def process_request(self, request):
        try:
            "Some DB Code"
            success = True
        except:
            success = False                

        request.db_connection_successful = success

Cache 'db_connection_successful' for performance.

jazz
  • 2,371
  • 19
  • 23