【问题标题】:Rendering a Django Form through a TemplateTag通过 TemplateTag 渲染 Django 表单
【发布时间】:2012-12-18 08:27:08
【问题描述】:

我正在尝试通过 django 中的模板标签呈现表单,以便可以在多个页面上呈现表单。但是,当我尝试渲染它时出现以下错误:

_ init_() 至少需要 2 个参数(给定 1 个)。

我相信这是因为模板标签没有将用户信息传递给表单。经过身份验证的用户应该是传递给表单的用户。

Forms.py:

class ExpressionForm(forms.ModelForm):
    class Meta(object):
        model = Expression
        exclude = ('user',)

    body = forms.CharField(widget=forms.Textarea(attrs={'rows': 2, 'cols': 19}), required=False, label=_('Body'))

    def __init__(self, user, *args, **kwargs):
        super(ExpressionForm, self).__init__(*args, **kwargs)
        self.fields['expressiontype'].queryset = ExpressionType.objects.all()
        self.fields['expressiontype'].required = True

在我的模板标签 .py 中:

@register.inclusion_tag('expressions/templatetags/express.html')
def express():
    return {'form': ExpressionForm()}

如何通过模板标签将用户传递给表单?谢谢:)

【问题讨论】:

  • 根据您的 init 您应该将用户传递给表单:ExpressionForm(user)
  • 现在完美运行,谢谢:)

标签: django django-forms django-templates templatetags


【解决方案1】:

文档详细说明了如何pass arguments into custom tags

您的另一个选择是调整您的标签so it is aware of the context

【讨论】:

    猜你喜欢
    • 2012-06-29
    • 2018-11-13
    • 1970-01-01
    • 2011-07-06
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 2018-12-22
    相关资源
    最近更新 更多