如何在Django中修复此错误 - 未定义的变量:etree

时间:2012-12-06 12:37:44

标签: django django-forms

我是一个新手:)我试图在这篇文章In a django form, How to make a field readonly (or disabled) so that it cannot be edited?中使用@Rune中的一个答案,但我在标题中有一个错误。

任何人都可以帮助我。我确实尝试过使用

  

来自lxml import etree - get error unresolved import:etree

和这个

  

从xml.etree导入ElementTree作为etree - 从import获取错误未定义变量:formstring

编码

class ReadOnlyWidget(forms.Select):

def __init__(self, initial_widget, *args, **kwargs):
    self.initial_widget = initial_widget
    super(ReadOnlyWidget, self).__init__(*args, **kwargs)

def render(self, *args, **kwargs):
    def guess_readonly_text(original_content):
        root = etree.formstring("<span>%s</span>" % original_content)

        for element in root:
            if element.tag == 'input':
                return element.get('value')

            if element.tag == 'select':
                for option in element:
                    if option.get('selected'):
                        return option.text

            if element.tag == 'textarea':
                return element.text

        return "N/A"

    original_content = self.initial_widget.render(*args, **kwargs)
    try:
        readonly_text = self.initial_widget.render_readonly(*args, **kwargs)
    except AttributeError:
        readonly_text = guess_readonly_text(original_content)

    return mark_safe("""<span class="hidden">%s</span>%s""" %(original_content, readonly_text))

提前谢谢。

1 个答案:

答案 0 :(得分:0)

应该是fromstring,而不是formstring