修改Solr Build Schema脚本时出现Django模板上下文错误求助
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:
Ensure Your Command Inherits Correctly & Defines Arguments Properly
Make sure your command extendsBaseCommandand defines arguments with the samedestvalues as the originaloptions_list—this ensures the template recognizes the variables.Pass the Parsed Options to the Template Context
In thehandle()method, you need to explicitly pass the parsed arguments (stored in**options) into the template context, just like the original command did withoptparseoptions.
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
destparameters inadd_argument()match the original option names (likeusingandindent) so the template can reference{{ options.using }}and{{ options.indent }}without issues. - We explicitly include
'options': optionsin the context—this is what was missing when you switched toargparse, causing the template context error. - If you added any custom arguments, make sure they're included in the
optionsdict passed to the context if the template needs them.
内容的提问来源于stack exchange,提问作者Emeasoba Tochi

