V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
yuhr123
V2EX  ›  Django

django 2.0 build-in form 自定义相关的问题

  •  
  •   yuhr123 ·
    yuhr123 · 2017-12-21 12:58:03 +08:00 · 2732 次点击
    这是一个创建于 2289 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我初次使用 django 2.0,目前在学习使用 build-in views 实现用户密码重置功能且已经实现了密码重置的完整业务逻辑。

    现在的问题是,由于内建表单的帮助提示和错误消息都是英文的,我想进一步自定义密码重置页面中的表单中的帮助文本和错误消息为更友好的中文信息。

    涉及的路由:

    path('accounts/reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(
            template_name='resetpass/confirm.html',
        ),name='password_reset_confirm'),
    

    confirm.html 模板内容:

        <form action="" method="post">
            {% csrf_token %}
            <table>
                {{ form }}
            </table>
            <input type="submit" value="确认">
        </form>
    

    查阅官方手册,了解到 PasswordResetConfirmView 这个内建的 auth 视图默认使用 SetPasswordForm,但究竟如何对这个内建表单类的属性做进一步的自定义就不知道了。

    1 条回复    2017-12-21 13:55:29 +08:00
    yuhr123
        1
    yuhr123  
    OP
       2017-12-21 13:55:29 +08:00
    没人回答我自己完善以下,虽然暂时没有找到的完美的解决方案。

    在官方仓库中找到这个类的定义:

    https://github.com/django/django/blob/master/django/contrib/auth/forms.py

    把需要自定义的部分复制过来,重新设置键值即可。

    例如,在 `forms.py` 中创建一个注入 `SetPasswordForm` 的类:

    ```python
    from django.contrib.auth.forms import SetPasswordForm

    class UserResetPassword(SetPasswordForm):
    error_messages = {
    'password_mismatch': '两次输入的密码不一致',
    }
    ```

    路由部分相应的修改为:

    ```python
    from myapp.forms import UserResetPassword

    path('accounts/reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(
    template_name='resetpass/confirm.html',
    form_class=UserResetPassword,
    ), name='password_reset_confirm'),
    ```

    这种方式只能自定义 `error_messages`,由于内建表单的 `help_text` 调用 `password_validator` 中定义的消息,所以暂时没有特别简单的办法进行自定义,可能还是需要自己创建密码验证类来实现。如果大家有好的方案,敬请指点。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1104 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 22:49 · PVG 06:49 · LAX 15:49 · JFK 18:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.