[英]Get field type in Django's login template
I'm trying to create custom template for Django's build-in login view. 我正在尝试为Django的内置登录视图创建自定义模板。 At the moment it looks like (
registration/login.html
): 目前看起来像(
registration/login.html
):
<form method="post">
{% csrf_token %}
{% for field in form %}
{% include 'registration/form_field.html' %}
{% endfor %}
<input class="btn btn-primary btn-block" type="submit" value="{% trans "Log in" %}">
</form>
And registration/form_field.html
file is: 而
registration/form_field.html
文件是:
<div class="form-group {% if field.errors %}has-error{% endif %}">
<input class="form-control" name="{{ field.name }}" placeholder="{{ field.label }}" {% if field.data %}value="{{ field.data }}"{% endif %} />
{% if field.errors %}
<span class='text-danger'>{{ field.errors|join:'<br>' }}</span>
{% endif %}
</div>
Everything works as expected, only problem is that password is shown in clear text. 一切都按预期工作,唯一的问题是密码以明文显示。
To solve this type="password"
should be set for password
field (and type="text"
for username
field). 为了解决这个问题,应该在
password
字段中设置type="password"
(在username
段中设置type="text"
)。
Is it possible to implement this using field
variable (ie something like {{ field.type }}
)? 是否可以使用
field
变量(即类似{{ field.type }}
变量)来实现?
You can implement a PasswordInput widget in your form definition, that will render as a password field with type="password". 您可以在表单定义中实现PasswordInput小部件,该小部件将呈现为type =“ password”的密码字段。
class ExampleForm(forms.Form):
password = forms.CharField(label='Password',
widget=forms.PasswordInput())
In the templates, 在模板中,
{{form.password}}
will render this field, which is the cleanest solution. 将呈现此字段,这是最干净的解决方案。
You may also access the type of the field (as you wanted), like this: 您还可以根据需要访问字段的类型,如下所示:
{{form.fields.password.widget.input_type}}
Note that if you'd like further customization beyond simply rendering the form, there's nothing wrong with just writing your own html for the fields. 请注意,如果您希望进一步定制而不只是渲染表单,那么只需为字段编写自己的html就没有错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.