有人可以建议如何实现自定义Django PasswordResetView吗?

时间:2019-07-12 15:10:48

标签: python django web django-rest-framework web-site-project

我想将密码重置链接发送到仅确认的电子邮件地址。用户还可以通过按用户名或电子邮件地址搜索来请求密码重设链接,而默认django中不提供此名称。我一直在尝试和编辑默认的django密码重置视图和表单很多天了。但不是为我工作。

1 个答案:

答案 0 :(得分:1)

您可以从以下位置扩展PasswordResetView rest_auth.views 并在其中做更多的逻辑 例如

from rest_auth.views import PasswordChangeView, PasswordResetView, PasswordResetConfirmView
sensitive_post_parameters_m = method_decorator(
    sensitive_post_parameters(
        'password', 'old_password', 'new_password1', 'new_password2'
    )
)

class PasswordResetViewNew(PasswordResetView):
    def post(self, request, *args, **kwargs):
        email = request.data.get('email')
        try:
            if User.objects.get(email=email).active:

                return super(PasswordResetViewNew, self).post(request, *args, **kwargs)
        except:
            # this for if the email is not in the db of the system
            return super(PasswordResetViewNew, self).post(request, *args, **kwargs)



网址

    path('password/reset/', PasswordResetViewNew.as_view()),

编辑以回答“如何通过用户名搜索以发送密码重置链接”

PasswordResetView包含的默认序列化器

email = serializers.EmailField()

这意味着终点将不接受除电子邮件之外的任何东西 因此我们将做一些技巧使其接受字符,以便我们向其发送用户名

首先,我们将扩展 来自rest_auth.serializers的PasswordResetSerializer 并做一些保养

from rest_auth.serializers import PasswordResetSerializer
from django.conf import settings
from django.contrib.auth.forms import PasswordResetForm

class TestSerializer(PasswordResetSerializer):
    email = serializers.CharField()
    # here changed the email to accept any chars
    reset_form = PasswordResetForm()

    def validate_email(self, value):
        #here we will trick it be make email really have the email of the username entered

        mutable = self.initial_data
        self.initial_data._mutable = True
        self.initial_data['email'] = User.objects.get(username=self.initial_data.get('email'))
        # don't forget to handle exception for username that not in db
        self.initial_data._mutable = mutable
        return super(TestSerializer, self).validate_email(value)

并在我们的视图中进行了如下更改

from django.utils.translation import gettext_lazy as _
#don't forget to import PasswordResetView, TestSerializer

class PasswordResetViewNew(PasswordResetView):
    serializer_class = TestSerializer
    # here we changed the default serializer to our new serializer
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.data['email'] = User.objects.get(username=serializer.data.get('email'))
        # here we trick it again and change the email with the email for the username entered
        serializer.save()
        # Return the success message with OK HTTP status
        return Response(
            {"detail": _("Password reset e-mail has been sent.")},
            status=status.HTTP_200_OK
        )