我想知道以下是否可行,需要一个例子。
我想创建一个呈现登录表单的模板标记。请这样做和指导。
这背后的原因是我有一个登录表单需要在我的网站的每个页面上。我已经决定这可以作为我可以包含的标签更好。我想使用我的forms.py中的表单而不是硬编码。
即
from django import template
from accounts.forms import AuthenticationForm
register = template.Library()
def authentication_form():
render this form == AuthenticationForm() ?????
答案 0 :(得分:4)
您需要创建一个inclusion tag,这是一个呈现模板的标记。
首先在名为_tag_auth_form.html
的文件中定义模板:
<form method="post" action="{{ action }}">
{% csrf_token %}
{{ form }}
<input type="submit" />
</form>
然后,您的模板标记只需使用适当的上下文变量呈现上述模板:
from django import template
from accounts.forms import AuthenticationForm
register = template.Library()
@register.inclusion_tag('_tag_auth_form.html')
def authentication_form():
return {'form': AuthenticationForm(), 'action': '/some/url'}