Error while trying to connect Django to SQL Server using django-mssql-backend

2.7k views Asked by At
Windows 10   
SQL Server 2019  
Python 3.9.1  
Django 3.2.5  

pip freeze: 
  asgiref==3.4.1  
  Django==3.2.5    
  django-mssql-backend==2.8.1  
  djangorestframework==3.12.4  
  pyodbc==4.0.30  
  pytz==2021.1  
  sqlparse==0.4.1 

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': 'dbForDjango',
        'USER': 'sa',
        'PASSWORD': 'sdf874sd21',
        'HOST': 'DESKTOP-AR76KF2\SQL_SERVER',
        'PORT': '',

        'OPTIONS': {
            'driver': 'ODBC Driver 17 for SQL Server',
        },
    },
}

I can run the server without any problem also py manage.py shell is working but Django can't communicate with the database at all.
The command "py manage.py dbshell" occurs this error:

enter image description here

Please ignore the directory name "playingWithFastAPI", am using Django not FastAPI :)

py manage.py migrate occurs that error:

enter image description here

2

There are 2 answers

2
Tim Nyborg On BEST ANSWER

The dbshell error is a known issue (see https://github.com/ESSolutions/django-mssql-backend/issues/100), as django-mssql-backend is not compatible with Django 3.1+

0
Sơn Nguyễn On

so with Django version more than 3.2, you must use mssql-django. https://learn.microsoft.com/en-us/samples/azure-samples/mssql-django-samples/mssql-django-samples/ and goodluck for you

py -m pip install django mssql-django

# settings.py
DATABASES = {
    "default": {
        "ENGINE": "mssql",
        "NAME": "DATABASE_NAME",
        "USER": "USER_NAME",
        "PASSWORD": "PASSWORD",
        "HOST": "HOST_ADDRESS",
        "PORT": "1433",
        "OPTIONS": {"driver": "ODBC Driver 17 for SQL Server", 
        },
    },
}