簡體   English   中英

如何配置Django以在MSSQL Server上運行

[英]How to configure Django to run on MSSQL Server

我可以用SQLite數據庫運行Django 1.11。 但是我收到了MSSQL Server的錯誤。

除了settings.py文件,我沒有修改任何東西。

它顯示了ImproperlyConfigured:不支持Django 1.11。
這是我的配置:

Settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django_pyodbc',
        'HOST': '127.0.0.1', 
        'NAME': 'demo2016',
        'USER': 'sa',
        'PASSWORD': '',
        'PORT': '',
        'OPTIONS': {
            'driver': 'ODBC Driver 13 for SQL Server',
        },
    }
}

在cmd提示符下:

C:\Users\Vitriv-Desktop\Desktop\sqldjango>python manage.py migrate

Traceback (most recent call last):
      File "manage.py", line 22, in <module>
        execute_from_command_line(sys.argv)
      File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line
        utility.execute()
      File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 338, in execute
        django.setup()
      File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup
        apps.populate(settings.INSTALLED_APPS)
      File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 108, in populate
        app_config.import_models()
      File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 202, in import_models
        self.models_module = import_module(models_module_name)
      File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 994, in _gcd_import
      File "<frozen importlib._bootstrap>", line 971, in _find_and_load
      File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 678, in exec_module
      File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
      File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\models.py", line 4, in <module>
        from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
      File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module>
        class AbstractBaseUser(models.Model):
      File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 124, in __new__
        new_class.add_to_class('_meta', Options(meta, app_label))
      File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 325, in add_to_class
        value.contribute_to_class(cls, name)
      File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\options.py", line 214, in contribute_to_class
        self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
      File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\__init__.py", line 33, in __getattr__
        return getattr(connections[DEFAULT_DB_ALIAS], item)
      File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\utils.py", line 211, in __getitem__
        backend = load_backend(db['ENGINE'])
      File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\utils.py", line 115, in load_backend
        return import_module('%s.base' % backend_name)
      File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django_pyodbc\base.py", line 98, in <module>
        raise ImproperlyConfigured("Django %d.%d is not supported." % DjangoVersion[:2])
    django.core.exceptions.ImproperlyConfigured: Django 1.11 is not supported.

應該是什么引擎:我已經改變了

'ENGINE':'django_pyodbc'到'ENGINE':'sqlserver'

之后它顯示出來

django.core.exceptions.ImproperlyConfigured: 'sqlserver' isn't an available database backend.
Try using 'django.db.backends.XXX', where XXX is one of:
    'mysql', 'oracle', 'postgresql', 'sqlite3'
Error was: No module named 'sqlserver'

之后我嘗試安裝sqlserver

C:\Windows\system32>pip install sqlserver
Collecting sqlserver
  Could not find a version that satisfies the requirement sqlserver (from versions: )
No matching distribution found for sqlserver

根據@Anusha Prashanth的回答

方法1:我試圖更改數據庫 - >'ENGINE':'sqlserver_ado'

結果:

C:\Users\Vitriv-Desktop\Desktop\sqldjango>python manage.py migrate
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 338, in execute
    django.setup()
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 108, in populate
    app_config.import_models()
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\models.py", line 4, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 124, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 325, in add_to_class
    value.contribute_to_class(cls, name)
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\options.py", line 214, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\__init__.py", line 33, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\utils.py", line 212, in __getitem__
    conn = backend.DatabaseWrapper(db, alias)
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sqlserver_ado\base.py", line 184, in __init__
    super(DatabaseWrapper, self).__init__(*args, **kwargs)
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\base.py", line 96, in __init__
    self.client = self.client_class(self)
TypeError: 'NoneType' object is not callable

方法2:我嘗試更改數據庫 - >'ENGINE':'sql_server.pyodbc'

結果:

來自models.py

import os
import mimetypes

from django.utils.translation import gettext as _
from django.conf import settings
from django.contrib.auth.models import User

from django.db import models

GENRE_CHOICES =  (
             ('1', 'Rock'),
             ('2', 'Jazz/Blues'),
             ('3', 'Blues'),    
             )


def get_upload_path(dirname, obj, filename):
   return os.path.join("audiotracks", dirname, obj.user.username, filename)

def get_audio_upload_path(obj, filename):
   return get_upload_path("audio_files", obj, filename)

class Genre(models.Model):
   genre_choices = models.CharField(max_length=1, choices=GENRE_CHOICES)
   slug = models.SlugField(max_length = 40, unique = True) #so as to have a dedicated page for each category 
   description = models.TextField()

def __unicode__(self):
       return self.title

def get_absolute_url(self):
    return "/genres/%s/" % self.slug

class AudioTrack(models.Model):
   class Meta:
      abstract = True

   user = models.ForeignKey(User, 
      related_name = "tracks",
      blank = True,
      null = True
  )

added_on = models.DateTimeField(auto_now_add=True, null = True)
updated_on = models.DateTimeField(auto_now=True, null = True)
audio_file = models.FileField(_("Audio file"), upload_to=get_audio_upload_path)
title = models.CharField(_("Title"), max_length="200", null=True)
description = models.TextField(_("Description"), null=True, blank=True)
slug = models.SlugField(max_length = 40, unique = True) #so as to have a dedicated page for each category 
genres = models.ManyToManyField(Genre)

def __unicode__(self):
    return "Track '%s' uploaded by '%s'" % (self.title, self.user.username)

@property
def mimetype(self):
    if not hasattr(self, '_mimetype'):
        self._mimetype = mimetypes.guess_type(self.audio_file.path)[0]
    return self._mimetype

@property
def filetype(self):
    if '/' in self.mimetype:
        type_names = {'mpeg': 'MP3', 'ogg': 'Ogg Vorbis', 'wave':'wav', 'FLAC':'FLA'}
        filetype = self.mimetype.split('/')[1]
        return type_names.get(filetype, filetype)
    else:
        return self.mimetype

@models.permalink
def get_absolute_url(self):
    # ('tracks.views.track_detail', [self.user.username, self.slug])
    return "/%s/%s/" %(self.genre, self.slug)

if hasattr(settings, 'AUDIOTRACKS_MODEL'):
   app_name, model_name = settings.AUDIOTRACKS_MODEL.split('.')
   Track = models.get_model(app_name, model_name)
else:
   class Track(AudioTrack):
      pass

在cmd提示符下:

C:\Users\Vitriv-Desktop\Desktop\mydjango>python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x040AE108>
Traceback (most recent call last):
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\base.py", line 213, in ensure_connection
    self.connect()
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\base.py", line 189, in connect
    self.connection = self.get_new_connection(conn_params)
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sql_server\pyodbc\base.py", line 309, in get_new_connection
    timeout=timeout)
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 13 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server [5].  (5) (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. (5)')

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 128, in inner_run
    self.check_migrations()
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 422, in check_migrations
    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 20, in __init__
    self.loader = MigrationLoader(self.connection)
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\loader.py", line 52, in __init__
    self.build_graph()
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\loader.py", line 209, in build_graph
    self.applied_migrations = recorder.applied_migrations()
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\recorder.py", line 65, in applied_migrations
    self.ensure_schema()
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\recorder.py", line 52, in ensure_schema
    if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()):
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\base.py", line 254, in cursor
    return self._cursor()
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\base.py", line 229, in _cursor
    self.ensure_connection()
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\base.py", line 213, in ensure_connection
    self.connect()
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\base.py", line 213, in ensure_connection
    self.connect()
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\base.py", line 189, in connect
    self.connection = self.get_new_connection(conn_params)
  File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sql_server\pyodbc\base.py", line 309, in get_new_connection
    timeout=timeout)
django.db.utils.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 13 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server [5].  (5) (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. (5)')

嘗試使用django-pyodbc-azure

  • 安裝pyodbc
  • 安裝django-pyodbc-azure

    pip install django-pyodbc-azure

  • 更改數據庫引擎

    ENGINE:'sql_server.pyodbc'

Settings.py

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', 
        }, 
    }, 
}

參考


要么

你可以使用django-mssql

  • 安裝django-mssql - 支持django 1.8

    pip install django-mssql

  • 將數據庫引擎更改為sqlserver_ado

    ENGINE':'sqlserver_ado'

Django本身不支持MSSQL。 您應該可以使用: Django MSSQL但請記住它只顯示1.8的支持,並且1.11可能存在一些問題。

你為什么要在Django上使用MSSQL? 如果是因為您在Microsoft環境中,請不要擔心 - 您可以非常輕松地安裝MySQL。 我可以看到使用MSSQL和Django的唯一原因是你需要訪問仍在更新的舊數據庫。 如果它們是舊的並且這是替換應用程序,那么您可以將數據導出到MySQL。

成功創作......特別感謝Anusha Prasanth,Manassehkatz,Ingaz,Jordanm和我的研究。 由於Django MSSQL數據庫后端的舊文檔在他們的網站中產生了歧義,不管Django的哪個版本與MSSQL一起使用。 仍在進行更新......

使用以下軟件配置:

  • Django 1.11.8(LTS)
  • MSSQL Server 2017
  • django_pyodbc_azure-1.11.0.0.dist

創建虛擬環境后,請按照以下步驟操作:

 DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': 'DESKTOP-C6RS3DO', 'NAME': 'demo2016', 'USER': 'sa', 'PASSWORD': 'sa', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, } } 

非常重要注意:使用服務器pc /筆記本電腦的名稱。 不要試圖使用
'主持人':'127.0.0.1',
因為它會導致錯誤

models.py中 (定義需要包含的任何類)

import os
import mimetypes

from django.utils.translation import gettext as _
from django.conf import settings
from django.contrib.auth.models import User

from django.db import models

GENRE_CHOICES =  (
             ('1', 'Rock'),
             ('2', 'Jazz/Blues'),
             ('3', 'Blues'),    
             )


def get_upload_path(dirname, obj, filename):
   return os.path.join("audiotracks", dirname, obj.user.username, filename)

def get_audio_upload_path(obj, filename):
   return get_upload_path("audio_files", obj, filename)

class Genre(models.Model):
   genre_choices = models.CharField(max_length=1, choices=GENRE_CHOICES)
   slug = models.SlugField(max_length = 40, unique = True) #so as to have a dedicated page for each category 
   description = models.TextField()

def __unicode__(self):
       return self.title

def get_absolute_url(self):
    return "/genres/%s/" % self.slug

class AudioTrack(models.Model):
   class Meta:
      abstract = True

   user = models.ForeignKey(User, 
      related_name = "tracks",
      blank = True,
      null = True
  )

added_on = models.DateTimeField(auto_now_add=True, null = True)
updated_on = models.DateTimeField(auto_now=True, null = True)
audio_file = models.FileField(_("Audio file"), upload_to=get_audio_upload_path)
title = models.CharField(_("Title"), max_length="200", null=True)
description = models.TextField(_("Description"), null=True, blank=True)
slug = models.SlugField(max_length = 40, unique = True) #so as to have a dedicated page for each category 
genres = models.ManyToManyField(Genre)

def __unicode__(self):
    return "Track '%s' uploaded by '%s'" % (self.title, self.user.username)

@property
def mimetype(self):
    if not hasattr(self, '_mimetype'):
        self._mimetype = mimetypes.guess_type(self.audio_file.path)[0]
    return self._mimetype

@property
def filetype(self):
    if '/' in self.mimetype:
        type_names = {'mpeg': 'MP3', 'ogg': 'Ogg Vorbis', 'wave':'wav', 'FLAC':'FLA'}
        filetype = self.mimetype.split('/')[1]
        return type_names.get(filetype, filetype)
    else:
        return self.mimetype

@models.permalink
def get_absolute_url(self):
    # ('tracks.views.track_detail', [self.user.username, self.slug])
    return "/%s/%s/" %(self.genre, self.slug)

if hasattr(settings, 'AUDIOTRACKS_MODEL'):
   app_name, model_name = settings.AUDIOTRACKS_MODEL.split('.')
   Track = models.get_model(app_name, model_name)
else:
   class Track(AudioTrack):
      pass

在CMD>

C:\Users\Vitriv-Desktop\Desktop\mydjango> python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying sessions.0001_initial... OK

之后在虛擬環境中運行此cmd,

python manage.py runserver

導航到http://127.0.0.1:8000/admin

類型:

python manage.py createsuperuser

而已。 有關更多文檔,請參閱docs djangoproject.com

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM