我是菜鸟:) 我正在尝试在这篇文章中使用@Rune 的答案之一在 django 表单中,如何使字段只读(或禁用)以使其无法编辑?但我有一个标题中所述的错误。
谁能帮我这个。我确实尝试使用
从 lxml 导入 etree - 获取错误未解决的导入:etree
还有这个
from xml.etree import ElementTree as 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))
先感谢您。