Реакция: NoReverseMatch: Обратное соответствие для 'password_reset_confirm' не найдено. 'password_reset_confirm' не является допустимой функцией представления или именем шаблона
Я использую React и Dj-Rest-Auth для аутентификации. Я смог настроить страницу входа, страницу регистрации и страницу подтверждения электронной почты. Но когда я пытаюсь настроить страницу сброса пароля, я получаю эту ошибку каждый раз, когда я отправляю адрес электронной почты в форме сброса пароля:
django | django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name.
Кто-нибудь знает, почему это происходит и как это можно исправить?
Вот как я все это установил:
urls.py
# API URLS
urlpatterns += [
# API base url
path("api/", include("config.api_router")),
# DRF auth token
path("auth-token/", obtain_auth_token),
path('dj-rest-auth/', include('dj_rest_auth.urls')),
path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls'))
]
reset.js
import { useState } from 'react';
import { Formik, Field, Form } from 'formik';
import axios from "axios"
import { API } from '../api'
export function Reset() {
const [loading, setLoading] = useState(false)
const [success, setSuccess] = useState(false)
function handleSubmit(values, { resetForm }) {
setLoading(true)
axios.post(API.auth.passwordReset, values)
.then(res => {
resetForm()
setSuccess(true)
})
.finally(() => setLoading(false))
}
return (
<div>
{success && "You will receive a verification email."}
{loading && "Loading..."}
<Formik
initialValues={{
email: '',
}}
onSubmit={handleSubmit}>
{({ errors, touched }) => (
<Form>
<Field name="email">
{({ field, form }) => (
<label className="mt-3 block">
<span className="text-gray-700">Email</span>
<input
{...field}
type="text"
className="
mt-1
block
w-full
rounded-md
border-gray-300
shadow-sm
focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50
"
placeholder=""
style={
form.touched.email && form.errors.email ? (
{ border: '2px solid var(--primary-red)'}
) : null
}
/>
</label>
)}
</Field>
<button className="mt-3 bg-blue-100 rounded-md shadow-sm text-lg px-5 py-3 hover:bg-blue-200"
type="submit">
Submit
</button>
</Form>
)}
</Formik>
</div>
)
}
App.js
<Route path="/login" element={<Login />} exact />
<Route path="/signup" element={<Signup />} exact />
<Route path="/reset" element={<Reset />} exact />
<Route path="/accounts/password_reset_confirm" element={<ResetConfirm />} exact />
<Route path="/accounts/confirm-email/:key" element={<ConfirmEmail />} exact />
Посмотрев ваш файл Api.js, я обнаружил, что он выглядит нормально. Я проверил документацию dj-rest-auth и обнаружил, что ваша проблема включена в FAQ (см. вопрос 2). Там они предлагают добавить шаблон url с именем password_reset_confirm, поэтому вы должны изменить ваш urls.py файл на что-то вроде:
# API URLS
urlpatterns += [
# sample url pattern from dj-rest-auth demo
path("password-reset/confirm/<uidb64>/<token>/",
TemplateView.as_view(template_name="password_reset_confirm.html"),
name='password_reset_confirm'),
# API base url
path("api/", include("config.api_router")),
# DRF auth token
path("auth-token/", obtain_auth_token),
path('dj-rest-auth/', include('dj_rest_auth.urls')),
path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls'))
]
Я использовал ту же структуру, которую они предоставляют в demo, но используя path вместо url. Чтобы увидеть, как должен выглядеть файл password_reset_confirm.html, вы можете проверить тот же файл в демо-версии (https://github.com/iMerica/dj-rest-auth/blob/8a460ecf9a72aec269b75160e5c97f7ed608e247/demo/templates/password_reset_confirm.html).
Кроме того, вы можете включить стандартные url, которые система аутентификации Django предоставляет для этого в django.contrib.auth (urls можно найти здесь, вы заметите, что в L26 есть шаблон url с именем password_reset_confirm). Другим способом решения проблемы было бы включить эти urls в ваш urls.py файл, как (см. https://docs.djangoproject.com/en/4.0/topics/auth/default/#using-the-views-1):
# API URLS
urlpatterns += [
# include urls from django.contrib.auth
path('dj-auth/', include('django.contrib.auth.urls')),
# API base url
path("api/", include("config.api_router")),
# DRF auth token
path("auth-token/", obtain_auth_token),
path('dj-rest-auth/', include('dj_rest_auth.urls')),
path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls'))
]