且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用我自己的自定义表单覆盖django-rest-auth中的表单?

更新时间:2023-10-27 19:30:58

解决方案应该是


  1. 在您的视图中未设置 PasswordResetFormCustom ,但在序列化程序中

  2. 使用 rest_auth PasswordResetView (不是Django的)

  1. not set PasswordResetFormCustom in your view but in your serializer
  2. use the rest_auth's PasswordResetView (not Django's)

示例:

from django.contrib.auth.forms import PasswordResetForm as DjangoPasswordResetForm
from rest_auth.serializers import (
    PasswordResetSerializer as RestAuthPasswordResetSerializer
)
from rest_auth.views import PasswordResetView as RestAuthPasswordResetView
from django.utils.translation import ugettext_lazy as _
from rest_framework.exceptions import ValidationError

class PasswordResetForm(DjangoPasswordResetForm):
    def get_users(self, email):
        users = tuple(super().get_users(email))
        if users:
            return users
        msg = _('"{email}" was not found in our system.')
        raise ValidationError({'email': msg.format(email=email)})


class PasswordResetSerializer(RestAuthPasswordResetSerializer):
    password_reset_form_class = PasswordResetForm


class PasswordResetView(RestAuthPasswordResetView):
    serializer_class = PasswordResetSerializer

    def __init__(self, *args, **kwargs):
        """Prints the name of the class if it is used."""
        print(self.__class__.__name__)
        super().__init__(*args, **kwargs)