Skip to main content
 首页 » 编程设计

python之Django Haystack之无法构建 solr 架构

2025年02月15日27cyq1162

当我尝试构建 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 

我正在数数以寻求帮助。

请您参考如下方法:

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

django-haystack 2.6.1 中的

haystack/management/commands/build_solr_schema.py:

     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.py 在 django-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.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 可以正常工作了!