反应:NoReverseMatch:找不到 'password_reset_confirm' 的反向。 'password_reset_confirm' 不是有效的视图函数或模式名称

React: NoReverseMatch: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name

我正在使用 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

const baseURL = "http://127.0.0.1:8000"
const apiURL = `${baseURL}/api`

export const API = {
    auth: {
        login: `${baseURL}/dj-rest-auth/login/`,
        logout: `${baseURL}/dj-rest-auth/logout/`,
        passwordReset: `${baseURL}/dj-rest-auth/password/reset/`,
        passwordResetConfirm: `${baseURL}/dj-rest-auth/password/reset/confirm/`,
        signup: `${baseURL}/dj-rest-auth/registration/`,
        verifyEmail: `${baseURL}/dj-rest-auth/registration/verify-email/`
    },
    facilities: {
        list: `${apiURL}/facilities/`,
        retrieve: id => `${apiURL}/facilities/${id}/`,
        update: id => `${apiURL}/facilities/${id}/update/`,
    }
}

Adapters.py

from typing import Any

from allauth.account.adapter import DefaultAccountAdapter
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from django.conf import settings
from django.http import HttpRequest


class AccountAdapter(DefaultAccountAdapter):
    def is_open_for_signup(self, request: HttpRequest):
        return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True)

    def send_mail(self, template_prefix, email, context):
        if settings.DEBUG:
            context["activate_url"] = (
                "http://localhost:3000/accounts/confirm-email/" + context["key"]
            )
        else:
            context["activate_url"] = (
                settings.FRONTEND_URL + "/accounts/confirm-email/" + context["key"]
            )
        return super().send_mail(template_prefix, email, context)


class SocialAccountAdapter(DefaultSocialAccountAdapter):
    def is_open_for_signup(self, request: HttpRequest, sociallogin: Any):
        return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True)

看到你的 Api.js 文件后,我觉得还不错。我检查了 dj-rest-auth 文档,发现您的问题包含在 FAQ 中(参见问题 2)。他们在那里建议我们需要添加名称为 password_reset_confirm 的 url 模式,因此您应该将 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 but using path instead of url. To see how the file password_reset_confirm.html file should look like you can check the same file in the demo (https://github.com/iMerica/dj-rest-auth/blob/8a460ecf9a72aec269b75160e5c97f7ed608e247/demo/templates/password_reset_confirm.html) 中提供的相同结构。

此外,您可以在 django.contrib.auth 中包含 Django 身份验证系统为此提供的默认 url(urls 可以在 here, you will notice there's a url pattern named password_reset_confirm in L26). So another way of solving the problem would be to include those urls in your urls.py file like (see 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'))
]