You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改Solr Build Schema脚本时出现Django模板上下文错误求助

Fixing Django Template Context Error When Modifying Haystack's build_solr_schema Command

Hey there, let's break down why you're hitting that template context error after switching from options_list to add_argument() in your custom build_solr_schema command, and how to fix it.

The Root Cause

Django 1.11 moved away from optparse (which uses options_list) to argparse (using add_argument()), but Haystack 2.4.0's original build_solr_schema command relies on passing the options object directly into the template context. When you switched to add_argument(), you might have missed ensuring the template gets all the expected variables from the parsed arguments, leading to the context error.

Step-by-Step Solution

Here's how to adjust your custom command to work correctly with argparse while maintaining compatibility with Haystack's template:

  1. Ensure Your Command Inherits Correctly & Defines Arguments Properly
    Make sure your command extends BaseCommand and defines arguments with the same dest values as the original options_list—this ensures the template recognizes the variables.

  2. Pass the Parsed Options to the Template Context
    In the handle() method, you need to explicitly pass the parsed arguments (stored in **options) into the template context, just like the original command did with optparse options.

Working Code Example

# encoding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
from django.core.management.base import BaseCommand, CommandError
from django.template import loader
from haystack import connections

class Command(BaseCommand):
    help = "Generates a Solr schema template for use with your Haystack setup."

    def add_arguments(self, parser):
        # Match the original option names/dest values to keep template compatibility
        parser.add_argument(
            '--using',
            action='store',
            dest='using',
            default='default',
            help='Which Solr connection to generate the schema for.',
        )
        parser.add_argument(
            '--indent',
            action='store',
            dest='indent',
            type=int,
            default=2,
            help='Number of spaces to use for indentation in the output.',
        )

    def handle(self, **options):
        try:
            backend = connections[options['using']].get_backend()
        except KeyError:
            raise CommandError(f"The connection '{options['using']}' doesn't exist in your settings.")

        if not hasattr(backend, 'build_schema'):
            raise CommandError(f"The backend '{options['using']}' doesn't support schema generation.")

        # Build the schema using Haystack's backend method
        unified_index = connections[options['using']].get_unified_index()
        schema_xml = backend.build_schema(unified_index.all_searchfields())

        # Load the template and pass the required context
        template = loader.get_template('haystack/solr.xml')
        context = {
            'schema': schema_xml,
            'options': options,  # This is critical for the template to access arguments
        }

        # Render and print the output
        output = template.render(context)
        print(output)

Key Notes

  • The dest parameters in add_argument() match the original option names (like using and indent) so the template can reference {{ options.using }} and {{ options.indent }} without issues.
  • We explicitly include 'options': options in the context—this is what was missing when you switched to argparse, causing the template context error.
  • If you added any custom arguments, make sure they're included in the options dict passed to the context if the template needs them.

内容的提问来源于stack exchange,提问作者Emeasoba Tochi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:42:30