密码字段以纯文本形式显示密码

password field is showing password in plain text

我已经使用django allauth 进行用户注册和登录系统。我可以通过使用 for 循环简化代码行来显示表单。我也为每个字段获得了正确的字段类型(TextInput 和 PasswordInput)。但是,具有 PasswordInput 的密码字段以纯文本形式显示密码。我该如何解决?

我的注册页面(account/signup.html)

<form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}">
    {% csrf_token %}
     {% for field in form.visible_fields %}
     <div class="form-group">
        <label for="{{ field.id_for_label}}">{{field.label}}</label>
        {{ field.errors.0 }}
        <input type="{{field|input_type}}" name="{{ field.name }}" class="form-control" id="{{ field.id_for_label}}">
     </div>
     {% endfor %}
</form>

filters.py

from django import template
register = template.Library()

@register.filter('input_type')
def input_type(field):
    print('field',field.field.widget.__class__)
    return field.field.widget.__class__.__name__

如何在点中显示密码?

您可以通过覆盖 class

表单中的 __init__ 方法来添加 class
def __init__(self, *args, **kwargs): 
    super().__init__(*args, **kwargs) 
    self.fields['password'].widget.attrs['class'] = 'form-control'

密码以纯文本显示,因为您分配的 <input> 类型不正确,因此没有像 <input type="password"> 那样隐藏密码。

通过阅读评论,您似乎正在尝试向表单字段添加自定义 bootstrap classes。正如 Anna Vracheva 所说,您可以使用表单的 __init__ 方法将 class 添加到字段中。

from django import forms

class CustomForm("""Whichever class you're inheriting from, probably ModelForm"""):
    # If you're using AllAuth, this is already defined on the form
    password = fields.CharField(widget=forms.PasswordInput) 
    # Or whatever field, for that matter

    def __init__(self, *args, **kwargs):
        super(CustomFieldForm, self).__init__(*args, **kwargs)

        # Option 1 - Assign to only password
        self.fields['password'].widget['class'] = 'form-control'

        # Option 2 - Loop over all fields and assign to all
        for field in self.fields:
            field.widget['class'] = 'form-control'

然后,让 Django 的模板来代替手动渲染 HTML:

<!-- This -->
{{ field }}
<-- -->
<!-- Instead of this -->
<input type="{{field|input_type}}" name="{{ field.name }}" 
       class="form-control" id="{{ field.id_for_label}}">

这应该可以解决您在保留表单时遇到的任何字段渲染问题 classes.

你也可以试试这个:

<input class="form-control" type="{{ field.field.widget.input_type }}"
                   name="{{ field.name }}"
                   id="id_{{ field.name }}" >