【问题标题】:python,django, solr, haystack: django templates context error when editing solr_build_schema BaseCommand.add_argument()python,django,solr,haystack:编辑 solr_build_schema BaseCommand.add_argument() 时 django 模板上下文错误
【发布时间】:2018-04-26 09:42:32
【问题描述】:

请帮助....我正在尝试在我的 django 站点搜索中使用 solr、pysolr 和 haystack。我已经编辑了 haystack build_solr_schema 脚本以使用 BaseCommand.add_argument(),删除了默认的 options_list。以下是我使用的版本; Python 3.5.2 Django 1.11.11 solr-7.3.0 django-haystack 2.4.0 pysolr 3.7.0

# encoding: utf-8

from __future__ import absolute_import, division, print_function, unicode_literals

import sys
from optparse import make_option
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand
from django.template import Context, loader
from haystack import constants
from haystack.backends.solr_backend import SolrSearchBackend

class Command(BaseCommand):
    help = "Generates a Solr schema that reflects the indexes."

    def add_arguments(self, parser):
        # positional arguments
        parser.add_argument("-f", "--filename", action="store", type="string", dest="filename",
                help='If provided, directs output to a file instead of stdout.',),
       # optional positional arguments
       parser.add_argument("-u", "--using", action="store", type="string", dest="using", default=constants.DEFAULT_ALIAS,
                help='If provided, chooses a connection to work with.')

      """
       base_options = (
       make_option("-f", "--filename", action="store", type=str, dest="filename",
                help='If provided, directs output to a file instead of stdout.'),
       make_option("-u", "--using", action="store", type=str, dest="using", default=constants.DEFAULT_ALIAS,
                help='If provided, chooses a connection to work with.'),
       )
      option_list = BaseCommand.option_list + base_options
      """
     def  handle(self, **options):
         """Generates a Solr schema that reflects the indexes."""
         using = options.get('using')
         schema_xml = self.build_template(using=using)

         if options.get('filename'):
            self.write_file(options.get('filename'), schema_xml)
         else:
             self.print_stdout(schema_xml)

    def build_context(self, using):
        from haystack import connections, connection_router
        backend = connections[using].get_backend()

        if not isinstance(backend, SolrSearchBackend):
            raise ImproperlyConfigured("'%s' isn't configured as a SolrEngine)." % backend.connection_alias)

        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')
        c = self.build_context(using=using)
        return t.render(c)

    def print_stdout(self, schema_xml):
        sys.stderr.write("\n")
        sys.stderr.write("\n")
        sys.stderr.write("\n")
        sys.stderr.write("Save the following output to 'schema.xml' and place it in your Solr configuration directory.\n")
        sys.stderr.write("--------------------------------------------------------------------------------------------\n")
        sys.stderr.write("\n")
        print(schema_xml)

    def write_file(self, filename, schema_xml):
        schema_file = open(filename, 'w')
        schema_file.write(schema_xml)
        schema_file.close()

给出的错误如下所示

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 364, in execute_from_command_line
utility.execute()
    File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 356, 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/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
    File "/home/tochie/virtual_django/myblog_env/mysite/venv/lib/python3.5/site-packages/haystack/management/commands/build_solr_schema.py", line 39, in handle
schema_xml = self.build_template(using=using)
    File "/home/tochie/virtual_django/myblog_env/mysite/venv/lib/python3.5/site-packages/haystack/management/commands/build_solr_schema.py", line 66, in build_template
    return t.render(c)
   File "/usr/local/lib/python3.5/dist-packages/django/template/backends/django.py", line 64, in render
    context = make_context(context, request, autoescape=self.backend.engine.autoescape)
   File "/usr/local/lib/python3.5/dist-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.

如果有任何其他方法可以解决此问题,请提供帮助,而无需编辑 haystack 的 build_solr_schema 或任何其他解决此问题的方法。谢谢

【问题讨论】:

    标签: python django solr django-haystack


    【解决方案1】:

    错误来自 Haystack,因此看起来您的 Haystack 版本不支持 Django 1.11。

    尝试升级 Haystack。 2.8.1 版是撰写本文时的最新版本,支持 Django 1.11。

    我在文档中找不到任何明确的内容,但 this commit 建议在 2.7 版中添加了对 Django 1.11 的支持。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-11
      • 2012-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      相关资源
      最近更新 更多