#django-rest-framework #django-allauth #django-rest-auth
#django-rest-framework #django-allauth #django-rest-auth
Вопрос:
Я использую Django Rest Auth с Django All Auth.
Когда я попадаю в конечную /rest-auth/password/reset/
точку (метод POST с адресом электронной почты) Я получаю электронное письмо, содержащее URL-адрес для сброса пароля.
И затем я нажимаю на URL, у меня появляется ошибка, подобная приведенной ниже:
ImproperlyConfigured at /password-reset/confirm/MzY/5l0-c1042120be1e07140e64/
TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'
В общем, после нажатия на этот URL-адрес экран должен перейти в браузер /rest-auth/password/reset/confirm/
.
Но в моем случае это работает не так…
Как я могу решить эту ошибку?
Вот коды:
project/urls.py
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')),
path('rest-auth/', include('rest_auth.urls')),
path('rest-auth/registration/', include('rest_auth.registration.urls')),
path('account-confirm-email/(?P<key>[-:w] )/$', TemplateView.as_view(),
name="account_confirm_email"),
path('account-confirm-email/', include('allauth.urls')),
re_path(
r'^password-reset/confirm/(?P<uidb64>[0-9A-Za-z_-] )/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
TemplateView.as_view(),
name='password_reset_confirm'),
]
serializers.py
from rest_auth.serializers import PasswordResetSerializer
class CustomPasswordResetSerializer(PasswordResetSerializer):
def get_email_options(self):
print("check override")
return {
'domain_override': 'localhost:8000',
'email_template_name': 'account/email/password_reset_key_message.txt',
}
password_reset_key_message.txt
A password reset has been requested.
Click the link below to continue.
{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
settings.py
REST_AUTH_SERIALIZERS = {
'PASSWORD_RESET_SERIALIZER': 'path.to.serializers.CustomPasswordResetSerializer',
}
python: 3.7.5
Django: 2.2.2
django-allauth: 0.41.0
django-rest-auth: 0.9.5
djangorestframework:3.12.1
Ответ №1:
Я понятия не имею об этих дополнительных библиотеках. Вы можете создать свой собственный пользовательский password_reset serializers
и views
, как показано ниже, убедитесь, что вы предоставляете аутентификацию на основе токена JWT при сбросе пароля от пользователя.
serializers.py
:
class ResetPasswordSerializer(Serializer):
new_password = serializers.CharField(error_messages={'required':' new_password key is required', 'blank':'new password is required'})
confirm_password = serializers.CharField(error_messages={'required':' confirm_password key is required', 'blank':'confirm password is required'})
views.py
:
class ForgotPasswordResetAPIView(APIView):
permission_classes = (IsAuthenticated,)
authentication_classes=[JSONWebTokenAuthentication,]
def post(self,request,*args,**kwargs):
data = request.data
user = request.user
print(user)
serializer = ResetPasswordSerializer(data=data)
if serializer.is_valid():
new_password = serializer.data.get("new_password")
confirm_password = serializer.data.get("confirm_password")
if new_password == confirm_password:
print('ok')
user.set_password(new_password)
user.save()
return Response({'success':"true",'message':'Your password have been reset successfully'},status=200)
return Response({'success':"False",'message':'Both password fields must be same'},status=400)
return Response(serializer.errors , status=400)