簡體   English   中英

使用路由器時無法在Django中創建超級用戶

[英]Fail to create a superuser in django, when use a router

我試圖用python3在Djago 1.11.4上創建mongodb / mysql項目。 我打算將mysql用於用戶身份驗證並將mongodb用於所有其他目的。 我精通創建一個用戶,但是創建超級用戶失敗。 當我嘗試創建超級用戶時,發生了以下情況:

$ python3 manage.py createsuperuser username=Admin
System check identified some issues:

WARNINGS:
?: (urls.W001) Your URL pattern '^$' uses include with a regex ending with a '$'. Remove the dollar from the regex to avoid problems including URLs.
Email address: admin@example.com
Password: 
Password (again): 
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute
    return super(Command, self).execute(*args, **options)
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 183, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/models.py", line 170, in create_superuser
    return self._create_user(username, email, password, **extra_fields)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/models.py", line 153, in _create_user
    user.save(using=self._db)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/base_user.py", line 80, in save
    super(AbstractBaseUser, self).save(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 807, in save
    force_update=force_update, update_fields=update_fields)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 834, in save_base
    with transaction.atomic(using=using, savepoint=False):
  File "/usr/local/lib/python3.5/dist-packages/django/db/transaction.py", line 158, in __enter__
    if not connection.get_autocommit():
  File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/base.py", line 385, in get_autocommit
    self.ensure_connection()
  File "/usr/local/lib/python3.5/dist-packages/django/db/backends/dummy/base.py", line 20, in complain
    raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.

這是我的settings.py的一部分:

DATABASES = {
    'default': {
        'ENGINE' : 'django.db.backends.dummy',
        'NAME' : 'my_database'
    },
    'users': {
        'NAME': 'nra_gpb_users',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'django'
    }
}
class AuthRouter(object):
    """
    A router to control all database operations on models in the
    auth application.
    """
    def db_for_read(model, **hints):
        """
        Attempts to read auth models go to auth_db.
        """
        if model._meta.app_label == 'auth':
            return 'users'
        return 'default'

    def db_for_write(model, **hints):
        """
        Attempts to write auth models go to auth_db.
        """
        print(model._meta.app_label)
        if model._meta.app_label == 'auth':
            return 'users'
        return 'default'

    def allow_relation(obj1, obj2, **hints):
        """
        Allow relations if a model in the auth app is involved.
        """
        return False

    def allow_migrate(db, app_label, model_name=None, **hints):
        """
        Make sure the auth app only appears in the 'auth_db'
        database.
        """
        return db == 'auth_db'
DATABASE_ROUTERS = [AuthRouter]

我成功地為用戶數據庫進行了遷移,並以交互方式成功創建了一個用戶:

Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.setup()
>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('Admin', 'admin@example.com', 'password')
>>> user.save()
>>> exit()

請向我解釋,出什么問題了?

UPD:成功創建具有以下內容的超級用戶:

python3 manage.py createsuperuser-數據庫用戶--username管理員

但是,當我嘗試授權時,再次收到ImproperConfigure錯誤:

$ python3 manage.py runserver
Performing system checks...

System check identified some issues:

WARNINGS:
?: (urls.W001) Your URL pattern '^$' uses include with a regex ending with a '$'. Remove the dollar from the regex to avoid problems including URLs.

System check identified 1 issue (0 silenced).
October 07, 2017 - 23:23:06
Django version 1.11.4, using settings 'my_django_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[07/Oct/2017 23:23:16] "GET /admin/ HTTP/1.1" 302 0
[07/Oct/2017 23:23:16] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1654
Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/sites.py", line 393, in login
    return LoginView.as_view(**defaults)(request)
  File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 67, in _wrapper
    return bound_func(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper
    return view(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 63, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 67, in _wrapper
    return bound_func(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 149, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 63, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 67, in _wrapper
    return bound_func(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 63, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/views.py", line 90, in dispatch
    return super(LoginView, self).dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/views/generic/edit.py", line 183, in post
    return self.form_valid(form)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/views.py", line 119, in form_valid
    auth_login(self.request, form.get_user())
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/__init__.py", line 139, in login
    request.session.cycle_key()
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/sessions/backends/base.py", line 311, in cycle_key
    self.create()
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/sessions/backends/db.py", line 50, in create
    self._session_key = self._get_new_session_key()
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/sessions/backends/base.py", line 164, in _get_new_session_key
    if not self.exists(session_key):
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/sessions/backends/db.py", line 46, in exists
    return self.model.objects.filter(session_key=session_key).exists()
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 670, in exists
    return self.query.has_results(using=self.db)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/query.py", line 517, in has_results
    return compiler.has_results()
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py", line 853, in has_results
    return bool(self.execute_sql(SINGLE))
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py", line 871, in execute_sql
    sql, params = self.as_sql()
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py", line 435, in as_sql
    from_, f_params = self.get_from_clause()
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py", line 660, in get_from_clause
    clause_sql, clause_params = self.compile(from_clause)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py", line 373, in compile
    sql, params = node.as_sql(self, self.connection)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/datastructures.py", line 144, in as_sql
    base_sql = compiler.quote_name_unless_alias(self.table_name)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/sql/compiler.py", line 364, in quote_name_unless_alias
    r = self.connection.ops.quote_name(name)
  File "/usr/local/lib/python3.5/dist-packages/django/db/backends/dummy/base.py", line 20, in complain
    raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
[07/Oct/2017 23:23:35] "POST /admin/login/?next=/admin/ HTTP/1.1" 500 207729

創建用戶時要使用的數據庫需要在終端中傳遞,因為默認的數據庫連接參數是虛擬的。

python3 manage.py createsuperuser --database users --username Admin

這是正確的settings.py部分,它使我成功進行了管理員授權:

INSTALLED_APPS = [
    'my_app',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles'
]
DATABASES = {
    'default': {
        'ENGINE' : 'django.db.backends.dummy',
        'NAME' : 'my_database'
    },
    'users': {
        'NAME': 'my_site_users',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'django'
    }
}
class AuthRouter(object):
    """
    A router to control all database operations on models in the
    auth application.
    """
    def db_for_read(model, **hints):
        """
        Attempts to read auth models go to auth_db.
        """
        if model._meta.app_label!='my_app':
            return 'users'
        return 'default'

    def db_for_write(model, **hints):
        """
        Attempts to write auth models go to auth_db.
        """
        if model._meta.app_label!='my_app':
            return 'users'
        return 'default'

    def allow_relation(obj1, obj2, **hints):
        """
        Allow relations if a model in the auth app is involved.
        """
        if obj1._meta.app_label == 'auth' or \
            obj2._meta.app_label == 'auth':
            return True
        return False

    def allow_migrate(db, app_label, model_name=None, **hints):
        """
        Make sure the auth app only appears in the 'auth_db'
        database.
        """
        return db == 'users'
DATABASE_ROUTERS = [AuthRouter]

正如@Oluwafemi Sule所述,在我的情況下,可以通過命令創建超級用戶:

python3 manage.py createsuperuser --database users --username Admin

暫無
暫無

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

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