connect SQL Server in django rather than default database - django

How to connect SQL Server in django rather than default database? What do I have to write in "settings.py" file?

You actually can install package for mssql:
pip install mssql-django
Then change your settings.py:
DATABASES = {
'default': {
'ENGINE': 'mssql',
'NAME': 'mydb',
'USER': 'user#myserver',
'PASSWORD': 'password',
'HOST': 'myserver.database.windows.net',
'PORT': '',
'OPTIONS': {
'driver': 'ODBC Driver 17 for SQL Server',
},
},
}
And btw you can turn off pyodbc's connection pooling by adding this in your settings:
DATABASE_CONNECTION_POOLING = False

Related

Getting a 'settings.DATABASES is improperly configured. Please supply the NAME value' error

I am using Django to connect to an on-premise database. Earlier, the database was hosted on Azure.
The connection string I used within Django settings earlier was as follows-
for sql database of Azure
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'NAME': 'DatabaseName', #notrealname
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'sql-django-uat.database.windows.net', #notreal
'PORT': '1433',
'OPTIONS': {
'driver': 'ODBC Driver 13 for SQL Server',
'MARS_Connection': 'True',
}
After the database migration, this string doesnt work. I keep getting 'Login timeout expired'.
But substituting 'NAME' with "DATABASE' works. Example given below-
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'DATABASE': 'DatabaseName', #notrealname
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'on-prem.local',
'PORT': '1433',
'OPTIONS': {
'driver': 'ODBC Driver 13 for SQL Server',
'MARS_Connection': 'True',
}
My webapp gets to the login page. But after I log in, I get the error- 'ImproperlyConfigured at /login/
settings.DATABASES is improperly configured. Please supply the NAME value.'
Can someone tell me how to solve this? I should mention leaving the "NAME" field blank also gives the same error. Thanks so much in advance.
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'NAME': 'DatabaseName', #notrealname
'USER': '<replace with on-premise DB Username>',
'PASSWORD': '<replace with on-premise DB password>',
'HOST': '<replace with database URL of on-premise DB URL>',
'PORT': '1433',
'OPTIONS': {
'driver': 'ODBC Driver 13 for SQL Server',
'MARS_Connection': 'True',
}
From the Azure SQL database, the settings.py should be:
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'NAME': 'mydb',
'USER': 'user#myserver',
'PASSWORD': 'password',
'HOST': 'myserver.database.windows.net',
'PORT': '',
'OPTIONS': {
'driver': 'ODBC Driver 13 for SQL Server',
},
},
}
# set this to False if you want to turn off pyodbc's connection pooling
DATABASE_CONNECTION_POOLING = False
USER: String. Database user name in "user" (on-premise) or "user#server" (Azure SQL Database) format. If not given then MS Integrated Security will be used.
Reference: django-pyodbc-azure 2.1.0.0
For on-premise SQL server, the database configuration:
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'HOST': '(LocalDB)\ProjectLocalDB',
'PORT': '',
'NAME': 'my_db',
'USER': 'my_user',
'PASSWORD': 'my_password',
'OPTIONS': {
'driver': 'ODBC Driver 13 for SQL Server',
},
},
}
Here are two tutorials, I think you can learn from them to check if you have missed something:
How to use Django with SQL Server LocalDB: This post has been
tested with Microsoft SQL Server 2017, Django 1.11.x and 2.x. The
pyodbc and django-pyodbc-azure packages will be used to connect
Django to SQL Server. The version of django-pyodbc-azure must match
your version of Django.
Django and MS SQL Server: The new python module/library is the django-pyodbc-azure which supports Django
2.0 and lower versions like Django 1.11.
Hope this helps.

with transaction.atomic() not working for Azure SQL Database

I use django-pyodbc-azure 2.1.0.0 for the connection with an Azure SQL database which works fine.
When I understand the documentation of django-pyodbc-azure correctly, transactions should be supported.
However, this code immediately updates the row. I would expect, that the row is updated after 20 seconds.
from django.db import transaction
from myapp.models import MyModel
import time
with transaction.atomic():
MyModel.objects.filter(id=1).update(my_field='Test')
time.sleep(20)
Am I doing something wrong? Do I need to specifiy certain settings on the Azure SQL database?
When I set AUTOCOMMIT = False in my database settings, then the following code will not update the row at all.
MyModel.objects.filter(id=1).update(my_field='Test')
time.sleep(20)
transaction.commit()
My current settings.py
'azure_reporting': {
'ENGINE': 'sql_server.pyodbc',
'NAME': 'reporting_db',
'HOST': 'xxxxxx.database.windows.net',
'PORT': '',
'USER': 'xxxx#xxxxxx.database.windows.net',
'PASSWORD': 'xxxxxx',
'OPTIONS': {
'driver': 'ODBC Driver 17 for SQL Server'
}
}
Please make sure you have set the AUTOCOMMIT=true on database settings:
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'HOST': 'yourserver.com',
'PORT': '1433',
'NAME': 'your_db',
'USER': 'your_user',
'PASSWORD': 'your_pw',
'AUTOCOMMIT': True,
'OPTIONS': {
'driver': 'ODBC Driver 13 for SQL Server',
},
},
}
No error happened, the only things what we can do is recheck the configuration of django-pyodbc-azure.
As you said: When I set AUTOCOMMIT = False in my database settings, then the following code will not update the row at all.
I think the transactions should works well.
Hope this helps.

Django always connects to localhost mongodb

I have followed the guide of db connection config:
https://nesdis.github.io/djongo/database-configuration/
However, it always connects to localhost one, not my setting's one.
Does anyone have any idea on this issue?
my packages versions:
Django 2.0
django-cors-headers 2.4.0
django-rest-auth 0.9.3
djangorestframework 3.9.0
djongo 1.1
mongoengine 0.16.3
pip 10.0.1
pymongo 3.7.2
urllib3 1.24.1
my settings
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'test_db',
'HOST': 'somewhere.com',
'PORT': 27017
}
}
Is seems that somewhere along the way, djongo changed the structure of the database settings. After wasting days trying to find the solution, I came across a page that had the updated structure, Try setting your DATABASE structure to this:
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'yourmongodb',
'CLIENT': {
'host': 'some-host.or.ip',
'port': 27017,
'username': 'youruser',
'password': 'yourdbpass',
'authSource': 'yourcollection',
}
},
}
Have you edited your setting in the settings.py file
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'XXXX',
'USER': 'XXX',
'PASSWORD': 'XXXX',
'HOST': 'XXX.XXX.XXX.XXX',
'PORT': '3306',
'OPTION': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
}
}
}
First: Create a SSH Tunnel to remote mysql server on localhost
ssh -N -L 3306:127.0.0.1:3306 root#192.168.0.122
192.168.0.122 >> is a remote LAN server of mine.
Second : use 127.0.0.1 as a HOST on Django connection string.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'XXXX',
'USER': 'XXX',
'PASSWORD': 'XXXX',
'HOST': '127.0.0.1',
'PORT': '3306',
'OPTION': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
}
}
OR change HOST to 127.0.0.1 in .env if using environment file.
This worked for me.

django-pyodbc and calling a stored procedure

I'm testing my code on Windows 10. I have a Django application that needs to call a stored procedure on a remote SQL Server database. Here's the DATABASES snippet from settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db1',
'HOST': 'mycompany.com',
'PORT': '3306',
'USER': 'user',
'PASSWORD': 'pw',
},
'ss': {
'ENGINE': 'django_pyodbc',
'NAME': 'db2',
'HOST': 'myserver\SQLEXPRESS',
'USER': 'myuser',
'PASSWORD': 'mypw',
'PORT': '1433',
# 'DRIVER': 'SQL Server',
'OPTIONS': {
'driver_supports_utf8': True,
'host_is_server': True, # must be True for remote db
'autocommit': True,
'unicode_results': True,
'extra_params': 'tds_version=8.0',
},
},
}
Here's a code snippet from my view:
cursor = connections['ss'].cursor()
cursor.execute("{call dbo.mysproc(?)}", (id))
When I execute the cursor.execute statement I get this error:
django.db.utils.DatabaseError: ('The SQL contains 1 parameter markers,
but 36 parameters were supplied', 'HY000')
My parameter, id, is a GUID.
Thoughts?
Here's the fix, simply changed the parentheses surrounding the parameter to square brackets:
cursor.execute("{call dbo.mysproc(?)}", [id])
I found this by trial and error.

How to add a remote postgres database in my django app?

What I'am trying to do is to use 2 databases in my django app. One is to be accessed from a remote server. Django settings has something like this
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'snackvoxadmin'
},
'users': {
.....
}
}
The database user has a url like similar to this one: postgres://a78adj1he81....
You can decompose your database url and configure it like this:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
And the pattern for a database url is :
postgres://user:password#host:post/database
https://docs.djangoproject.com/en/1.8/ref/settings/#databases
Or you can use the package dj-database-url to directly use the database url.
E.g. from readme :
import dj_database_url
DATABASES = {'default': dj_database_url.parse('postgres://...')}
That URL presumably consists of a username, a password, and a host name/IP address. You could split them up yourself or use the dj-database-url library.