【问题标题】:Django PasswordInputDjango 密码输入
【发布时间】:2014-02-15 18:56:54
【问题描述】:

我正在使用 PasswordInput,作为可选属性。

models.py

​​>
password = models.CharField(_('Site Password'), max_length=128,
    blank=True, null=True)

forms.py

​​>
from django.forms import PasswordInput

...

class Meta:
    model = ...
    widgets = {
        'password': PasswordInput(),
    }

按预期工作。然而,使用这个小部件意味着一旦密码被设置一次,就无法清除这个输入!

我希望有类似 AdminFileWidget 的东西,其中有一个选项可以通过选择“清除”复选框来清除图像/文件。

其他选项是向 ModelForm 添加一个额外的“clear_password”字段。

clear_password = forms.BooleanField(label=_('Clear'), initial=False,
                                    required=False)

并在保存方法中清除密码:

def save(self, commit=True):
    ...

    if self.cleaned_data['clear_password']:
        obj.password = None
    else:
        # Save the provided password in hashed format
        obj.password = make_password(self.cleaned_data['password'])

这也有效。但我希望有一个更清洁的解决方案..

我查看了 django.forms.widgets.ClearableFileInput .. 但对于像我这样的新手来说太复杂了:-(。

任何帮助将不胜感激。非常感谢

【问题讨论】:

  • 听起来你需要一个新的复合小部件。
  • 什么是“复合小部件”?我有很多东西要学..你能指出我正确的方向吗..快速谷歌搜索没有返回任何东西!

标签: django django-forms django-admin


【解决方案1】:

您可以通过将空值传递给 value 属性来清除表单的值。

类似的东西:

from django.forms import PasswordInput
from models import YourModel

password = forms.PasswordInput(attrs={'value': ''})

class Meta:
    model = YourModel

【讨论】:

  • 我不确定这如何解决我的问题。我仍然无法清除密码字段..一旦设置一次。但感谢您的建议。欣赏它。
猜你喜欢
  • 1970-01-01
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 2021-11-09
  • 2014-05-11
  • 1970-01-01
  • 2015-12-03
  • 2012-03-08
相关资源
最近更新 更多