Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test a database connection in Django?

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.

like image 918
Renyi Avatar asked Oct 11 '22 09:10

Renyi


1 Answers

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.

like image 66
jazz Avatar answered Oct 12 '22 23:10

jazz