将对象从模板标记传递到视图

时间:2013-06-20 06:52:28

标签: python django django-templates

Django版本:1.2.3

我想将Form对象从模板标记传递到此标记的专用视图。我的代码如下:

    from django import template
    from django.core.urlresolvers import reverse
    from django.utils.translation import ugettext, gettext_lazy as _
    from django.conf import settings
    from django.utils import simplejson 

    register = template.Library()

    ........

    @register.inclusion_tag('template.html', takes_context=True)
    def asset_diskencryption_settings(context, var1, form):

    context["form"] = form
    context["var1"] = var1

    return '' // Probably I have to use some method which allows me to return some variables to the template

在template.html中,我想使用表格变量,例如{{form.password}}

1 个答案:

答案 0 :(得分:2)

要设置变量,您应该使用assignment tag

@register.assignment_tag(takes_context=True)
def get_form(context, my_variable):
    form = Form() # do you stuff here
    return form

并使用它:

{% get_form 'my_variable' as form %}
{{ form.password }}