Using mssql-django, we can connect Django to MSSQL(SQL Server) with Windows Authentication and SQL Server Authentication. *I use SQL Server 2019 Express.
With Windows Authentication, to connect Django to MSSQL using mssql-django, set the code below to "settings.py". This code below is the example of Django and MSSQL in the same Windows Computer(localhost) and "ENGINE" must be "mssql" and "NAME" is for Database name "test" and "DESKTOP-QVRCPTA" for "HOST" is Windows Computer Name(Device name). *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', # DB name "test"
'HOST':'DESKTOP-QVRCPTA\SQLEXPRESS', # <server>\<instance>
'PORT':'', # Keep it blank
'OPTIONS': {
'driver': 'ODBC Driver 17 for SQL Server',
},
}
}
In addition, "DESKTOP-QVRCPTA" can be replaced with "localhost" and "USER" and "PASSWORD" can be put with empty string and "PORT" can be removed as shown below to connect Django to MSSQL with Windows Authentication:
# "settings.py"
DATABASES = {
'default':{
'ENGINE':'mssql',
'NAME':'test',
'USER':'', # Keep it blank
'PASSWORD':'', # Keep it blank
'HOST':'localhost\SQLEXPRESS', # "localhost" is also possible
# 'PORT':'', # Can be removed
'OPTIONS': {
'driver': 'ODBC Driver 17 for SQL Server',
},
}
}
With SQL Server Authentication, to connect Django to MSSQL using mssql-django, set the code for Windows Authentication as shown above with "USER" and "PASSWORD" to "settings.py". *The difference between the code for Windows Authentication and SQL Server Authentication is only "USER" and "PASSWORD":
# "settings.py"
DATABASES = {
'default':{
'ENGINE':'mssql',
'NAME':'test',
'USER':'john', # Username "john"
'PASSWORD':'johnpw', # Password "johnpw"
'HOST':'DESKTOP-QVRCPTA\SQLEXPRESS',
'PORT':'',
'OPTIONS': {
'driver': 'ODBC Driver 17 for SQL Server',
},
}
}
In addition, same as the code for Windows Authentication, "DESKTOP-QVRCPTA" can be replaced with "localhost" and "PORT" can be removed as shown below to connect Django to MSSQL with SQL Server Authentication:
# "settings.py"
DATABASES = {
'default':{
'ENGINE':'mssql',
'NAME':'test',
'USER':'john',
'PASSWORD':'johnpw',
'HOST':'localhost\SQLEXPRESS', # "localhost" is also possible
# 'PORT':'', # Can be removed
'OPTIONS': {
'driver': 'ODBC Driver 17 for SQL Server',
},
}
}
Next, install the latest package mssql-django:
pip install mssql-django
Then, make migrations and migrate:
python manage.py makemigrations && python manage.py migrate
Then, create superuser:
python manage.py createsuperuser
Now, we could connect Django to MSSQL with Windows Authentication and SQL Server Authentication, then create the tables for "test" database.