Jay Desai
Jay Desai

Reputation: 861

Getting error while using SQL Server database at the back end of django application

I'm trying to use local SQL Server database as a default database in django application. I have declared database in setting.py file as below:

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': 'Test',
        'USER': 'sa',
        'PASSWORD': 'P@ssw0rd1234',
        'HOST': 'DAL1281',
        'PORT': '1433',
        'OPTIONS': {
            'driver': 'ODBC Driver 13 for SQL Server',
            'host_is_server': True
        },
    },
}

While running the server I am getting below error:

django.db.utils.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 13 for SQL Server]TCP Provider: No connection could be made because the target machine actively refused it.\r\n (10061) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 13 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 13 for SQL Server]Invalid connection string attribute (0); [08001] [Microsoft][ODBC Driver 13 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (10061)')

I'm able to connect to database using SSMS. Also I have checked TCP/IP protocol is enabled in SQL Server Configuration Manager.

Upvotes: 2

Views: 3002

Answers (2)

You can use the latest package mssql-django to connect Django to MSSQL(SQL Server) with SQL Server Authentication. *I use SQL Server 2019 Express.

So, try this code below. *"ENGINE" must be "mssql" and "HOST" should be "<server>\<instance>" and keep it blank for "PORT" because there will be error if setting any port number e.g. "2244", "9877" or even "1433" which is the default port number of MSSQL:

# "settings.py"

DATABASES = {
    'default': {
        'ENGINE': 'mssql',           # Must be "mssql"
        'NAME': 'Test',
        'USER': 'sa',
        'PASSWORD': 'P@ssw0rd1234',
        'HOST': 'DAL1281\something', # <server>\<instance>
        'PORT': '',                  # Keep it empty
        # 'PORT': '1433',
        'OPTIONS': {
            'driver': 'ODBC Driver 17 for SQL Server',
        },
    },
}

Upvotes: 2

Davide Pizzolato
Davide Pizzolato

Reputation: 715

Try with this configuration:

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'HOST': '127.0.0.1',
        'PORT': '',
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PWD',
        'OPTIONS': {
            'driver': 'ODBC Driver 17 for SQL Server',
        },
    }
}

Upvotes: 1

Related Questions