【问题标题】:Django Haystack - unable to build solr schemaDjango Haystack - 无法构建 solr 架构
【发布时间】:2017-09-23 10:14:06
【问题描述】:

当我尝试构建 solr 架构时出现以下错误:

(my_env) pecan@tux ~/Documents/Django/mysite $ python manage.py build_solr_schema
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/core/management/__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/management/commands/build_solr_schema.py", line 29, in handle
    schema_xml = self.build_template(using=using)
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/management/commands/build_solr_schema.py", line 57, in build_template
    return t.render(c)
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/template/backends/django.py", line 64, in render
    context = make_context(context, request, autoescape=self.backend.engine.autoescape)
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/template/context.py", line 287, in make_context
    raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
TypeError: context must be a dict rather than Context.

也许这些信息会有用:

mysite/settings.py 文件:

"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 1.11.5.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '****'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

SITE_ID = 1

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django.contrib.sitemaps',
    'blog',
    'taggit',
    'haystack',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'

HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
        'URL': 'http://127.0.0.1:8983/solr/blog'
    },
}

blog/search_indexes.py 文件:

from haystack import indexes
from .models import Post

class PostIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    publish = indexes.DateTimeField(model_attr='publish')

    def get_model(self):
        return Post

    def index_queryset(self, using=None):
        return self.get_model().published.all()

blog/templates/search/indexes/blog/post_text.txt 文件:

{{ object.title }}
{{ object.tags.all|join:", " }}
{{ object.body }}

我正在使用 Apache Solr 4.10.4、Python 3.4.5 和 Django 1.11.5。当我尝试在 Python 控制台中导入 haystack 时,出现以下错误:

>>> import haystack
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/__init__.py", line 10, in <module>
    from haystack.constants import DEFAULT_ALIAS
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/constants.py", line 10, in <module>
    ID = getattr(settings, 'HAYSTACK_ID_FIELD', 'id')
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/conf/__init__.py", line 56, in __getattr__
    self._setup(name)
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/conf/__init__.py", line 39, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting HAYSTACK_ID_FIELD, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.in Python console

我正在寻求帮助。

【问题讨论】:

    标签: python django solr


    【解决方案1】:

    我的 Django 项目中的 Haystack 版本错误。我使用了django-haystack 2.6.1 包,但它在 django 模板上下文传递方面存在问题。这个版本在上下文中传递了一个上下文对象而不是字典。更多详情:https://github.com/django-haystack/django-haystack/pull/1504/commits/295584314e19a191a59450e053b21809adceca2a

    haystack/management/commands/build_solr_schema.pydjango-haystack 2.6.1

         content_field_name, fields = backend.build_schema(
             connections[using].get_unified_index().all_searchfields()
         )
         return Context({
             'content_field_name': content_field_name,
             'fields': fields,
             'default_operator': constants.DEFAULT_OPERATOR,
             'ID': constants.ID,
             'DJANGO_CT': constants.DJANGO_CT,
             'DJANGO_ID': constants.DJANGO_ID,
         })
    
     def build_template(self, using):
         t = loader.get_template('search_configuration/solr.xml')
    

    haystack/management/commands/build_solr_schema.pydjango-haystack 2.7.dev0

         content_field_name, fields = backend.build_schema(
             connections[using].get_unified_index().all_searchfields()
         )
    
         return {
             'content_field_name': content_field_name,
             'fields': fields,
             'default_operator': constants.DEFAULT_OPERATOR,
             'ID': constants.ID,
             'DJANGO_CT': constants.DJANGO_CT,
             'DJANGO_ID': constants.DJANGO_ID,
         }
    
     def build_template(self, using):
         t = loader.get_template('search_configuration/solr.xml')
    

    我不得不卸载 django-haystack 2.6.1 并使用命令安装更新版本:

    pip uninstall django-haystack
    pip install django-haystack==2.7.dev0
    

    我还解决了导入错误。在这种情况下,我只是将行 HAYSTACK_ID_FIELD = 1 添加到 settings.py 文件,并将所需的环境变量 DJANGO_SETTINGS_MODULE 设置为值 mysite.settings

    我在编辑 settings.py 后执行了以下命令:

    (my_env) pecan@tux ~/Documents/Django/mysite $ DJANGO_SETTINGS_MODULE="mysite.settings"
    (my_env) pecan@tux ~/Documents/Django/mysite $ echo $DJANGO_SETTINGS_MODULE 
    mysite.settings
    (my_env) pecan@tux ~/Documents/Django/mysite $ DJANGO_SETTINGS_MODULE python
    bash: DJANGO_SETTINGS_MODULE: command not found
    (my_env) pecan@tux ~/Documents/Django/mysite $ python
    Python 3.4.5 (default, Sep 17 2017, 18:19:56) 
    [GCC 5.4.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import haystack
    >>> 
    

    现在django-haystack 工作正常!

    【讨论】:

      【解决方案2】:

      调试 Haystack

      人们第一次使用 Haystack 时会遇到一些常见问题。

      “没有名为 haystack 的模块。”

      此问题通常在首次将 Haystack 添加到您的项目时出现。

      • 您是否使用了django-haystack 中的haystack 目录 结帐/安装?

      • haystack 目录在您的PYTHONPATH 上吗?或者,是 haystack 符号链接到您的项目中?

      • 启动一个 Django shell (./manage.py shell) 并尝试import haystack。你 可能会收到不同的、更具描述性的错误消息。

      • 仔细检查以确保您没有循环导入。 (即模块 A 尝试从尝试从模块导入的模块 B 导入 A.)

      “未找到任何结果。” (在网页上)

      有几个问题可能导致找不到结果。最常见的情况是,要么没有运行 rebuild_index 来填充索引,要么有一个空白的 document=True 字段,导致引擎没有内容可供搜索。

      • 您在已安装的应用程序中是否有 search_indexes.py

      • 您的数据库中有数据吗?

      • 你有没有运行./manage.py rebuild_index 来索引你所有的 内容?

      • 尝试运行 ./manage.py rebuild_index -v2 以获得更详细的输出到 确保正在处理/插入数据。

      • 启动一个 Django shell (./manage.py shell) 并尝试:

      从 haystack.query 导入 SearchQuerySet

      sqs = SearchQuerySet().all()

      sqs.count()

      • 您应该返回一个大于 0 的整数。如果不是,请检查上述内容并 重新索引。

      sqs[0] # 应该返回一个 SearchResult 对象。

      sqs[0].id # 应该得到类似'myapp.mymodel.1'的东西。

      sqs[0].text # ... 或者你的 document=True 字段是什么。

      • 如果您返回u''None,则表示您的数据未返回 使其成为被搜索的主要领域。你需要检查 该字段要么具有使用模型数据的模板,要么 model_attr 直接从模型中提取数据或 prepare/prepare_FOO 在索引时填充数据的方法。
      • 检查搜索页面的模板并确保它正在循环 结果正确。还要确保它要么访问有效 从搜索引擎返回的字段或它正在尝试的字段 通过{{ result.object.foo }} 查找访问关联模型。

      来源:http://django-haystack.readthedocs.io/en/v2.4.1/toc.html

      【讨论】:

      • 对不起,这个答案没有帮助。我在自己的回答中描述了我是如何解决这个问题的。
      猜你喜欢
      • 2012-10-15
      • 2012-11-28
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      相关资源
      最近更新 更多