使用Django& amp; WTForms

时间:2011-05-17 21:51:41

标签: django mongoengine wtforms

我正在尝试使用带有Django&amp ;;的WTForms。 MongoEngine / MongoDB数据库后端。表格输出正确,但我不能为我的生活得到标签出现。

这是我的模板代码:

{% load wtforms %}
<form>
    {% for f in form %}
        {{ f.label }}: {% form_field f %}<br/>
    {% endfor %}
</form>

这是我在视图中传递的内容:

form = StrandForm()
return render_to_response('create_strand.html', locals(), context_instance = RequestContext(request))

StrandForm类我尝试过从WTForm mongoengine扩展的model_form类和WTForm的Form类创建。标签存在于视图中,我可以将其打印到控制台并显示渲染的表单标签,但在转移到模板时它会以某种方式丢失。我做错了吗?

2 个答案:

答案 0 :(得分:1)

Django 1.4有一个新功能:do_not_call_in_templates属性。

如果在wtforms.Field类上设置它,则每个子类都会继承,并且所有字段都可以在django模板中正常工作。

import wtforms
wtforms.Field.do_not_call_in_templates = True

现在,以下代码按预期工作:

{% load wtforms %}
{{ f.label }}: {% form_field f %}

答案 1 :(得分:0)

我今天遇到了同样的问题。它与WTForms的编程方式有关,因此它可以与许多不同的模板库一起使用。 Django 1.3只会看到 f 作为HTML字符串,即使它有其他属性。

要解决此问题,您必须添加模板标记以检索属性。

将以下内容添加到项目层次结构中:

  • templatetags
  • templatetags / init .py
  • templatetags / templatetags
  • templatetags / templatetags / init .py
  • templatetags / templatetags / getattribute.py

然后在您的settings.py文件中,将以下行添加到 INSTALLED_APPS

'templatetags',

打开getattribute.py并粘贴以下代码:

from django import template
from django.conf import settings

register = template.Library()

@register.tag
def getattribute(parser, token):
    try:
        tag_name, tag_object, tag_function = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError("%r tag requires two arguments" % token.contents.split()[0])
    return getattrNode(tag_object, tag_function)

class getattrNode(template.Node):
    def __init__(self, tag_object, tag_function):
        self.tag_object = tag_object
        self.tag_function = tag_function
    def render(self, context):
        return getattr(context[self.tag_object], self.tag_function)()

这样,只要您在模板中并且需要一个不会显示的属性,就可以使用以下代码:

{% load getattribute %}
{% getattribute OBJECT ATTRIBUTE %}

在你的情况下:

{% getattribute f label %}

希望有所帮助!