我有一个模板标记,可以为我呈现一些自定义表单小部件。当我升级到Django 1.8时,它停止了工作。我试图弄清楚如何解决这个问题。
最终在表单字段的模板中呈现的是:
<project.appname.widgets.RadioFeedbackInput object at 0x10a8e5d50>
下面,在模板标签中,我认为问题出在render_to_string中。有什么建议吗?
这是我的模板标签:
from django import template
from django.template import loader, RequestContext
from django.template.defaultfilters import slugify
register = template.Library()
@register.tag
def render_form(parser, token):
"""Renders dynamic form accordingly"""
bits = token.split_contents()
if len(bits) < 2:
raise template.TemplateSyntaxError("%r tag takes at least one argument" % bits[0])
form = bits[1]
args = {}
# Parse extra "asvar" if given
if len(bits) > 2:
biter = iter(bits[2:])
for bit in biter:
if bit == "as":
args["asvar"] = biter.next()
else:
raise template.TemplateSyntaxError("%r tag got an unknown argument: %r" % (bits[0], bit))
return RenderFormNode(form, **args)
class RenderFormNode(template.Node):
def __init__(self, form, asvar=None):
self.form = form
self.asvar = asvar
def render(self, context):
context = context or {}
form = template.Variable(self.form).resolve(context)
try:
request = template.Variable('request').resolve(context)
except template.VariableDoesNotExist:
raise template.VariableDoesNotExist("The `render_form` template tag requires that the request context processor be enabled.")
# The question type is used to build out the template type.
template_path_context = {
'type': slugify(form.template_type)
}
template_list = [
'appname/question_types/%(type)s/form.html' % template_path_context,
'appname/question_types/%(type)s.html' % template_path_context,
'appname/%(type)s/form.html' % template_path_context,
'appname/form.html' % template_path_context
]
# Renders form, and saves to self.asvar if requested
context.update({'form': form})
rendered = loader.render_to_string(
template_list,
context
)
if self.asvar:
context[self.asvar] = rendered
return ''
return rendered
这里是小部件模板:
<div class="radio-button-block">
{% for fields in form %}
{% if forloop.first %}
<label>{{ fields.label|linebreaks }}</label>
<div class="radio-button">
{% endif %}
{% for field in fields %}
<div class="field">
{{ field }}
{% if field.errors %}
{% for error in field.errors %}
<div class="ui negative message">
{{ error }}
</div>
{% endfor %}
{% endif %}
{% if field.choice_feedback %}
<div class="feedback">
{{ field.choice_feedback|linebreaks }}
<a class="close-feedback ss-icon">close</a>
</div>
{% endif %}
</div>
{% endfor %}
{% endfor %}
</div>
</div>