首页 > 解决方案 > Django:NoReverseMatch 不是有效的视图函数或模式名称

问题描述

我有一个结构如下的 django 项目:

my_project
|_ UserSignUp
  |_ urls.py
  |_ views.py
|_ Mainpage
  |_ urls.py
  |_ views.py
|_ my_project
  |_ urls.py
  |_ settings.py

我的问题如下:我可以访问mysite.com/index并且mysite.com/login很好。但是如果我尝试打开mysite.com/signup我会遇到一个500 Internal Server Error,更准确地说是抛出一个错误:

NoReverseMatch at /signup/
Reverse for 'login' 未找到。'login' 不是有效的视图函数或模式名称。

关闭,因为我已经用谷歌搜索了错误,但没有遇到任何特别有用的东西。我发现的描述解释了错误,其中尝试访问应用程序的 url,然后由于 url 标记中未提供应用程序的命名空间而失败。在我的情况下,我在一个应用程序中,想要访问项目根目录的 url。据我所知,它应该会自动解决,即使没有,我也不知道如何告诉 django 请查看根 url。是 django 没有检查根 url 真的是问题的原因还是我设置错误的另一件事?我怎样才能解决这个问题?

我的根urls.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('', include('Mainpage.urls')),
    path('index/', include('Mainpage.urls')),
    path('mainpage/', include('Mainpage.urls')),
    path('home/', include('Mainpage.urls')),
    path('login/', auth_views.LoginView.as_view(template_name='login/login.html', redirect_field_name='index')),
    path('signup/', include('UserSignUp.urls')),
    path('logout', auth_views.LogoutView.as_view(template_name='logout/logout.html', next_page='index')),
    path('admin/', admin.site.urls),
]

我的用户注册urls.py

from django.urls import path
from django.conf.urls import include
from UserSignUp import views

urlpatterns = [
    path(r'', views.signup, name='signup'),
    path(r'account_activation_sent/', views.account_activation_sent, name='account_activation_sent'),
    path(r'activate/', views.activate, name='activate')
]

我的用户注册views.py

from django.contrib.auth import login
from django.contrib.auth.models import User
from django.contrib.sites.shortcuts import get_current_site
from django.shortcuts import render, redirect
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.template.loader import render_to_string
from UserSignUp.forms import SignUpForm
from UserSignUp.tokens import account_activation_token


def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(request)
            subject = 'Activate Your MySite Account'
            message = render_to_string('account_activation_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': account_activation_token.make_token(user),
            })
            user.email_user(subject, message)
            return redirect('signup/account_activation_sent')
    else:
        form = SignUpForm()
    return render(request, 'UserSignUp/signup.html', {'form': form})


def account_activation_sent(request):
    return render(request, 'UserSignUp/account_activation_sent.html')


def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except (TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None

    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.profile.email_confirmed = True
        user.save()
        login(request, user)
        return redirect('index')
    else:
        return render(request, 'UserSignUp/account_activation_invalid.html')

signup.html: _

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Signup</title>
  </head>
  <body>
    <header>
      <h1>My Site</h1>
      {% if user.is_authenticated %}
        <a href="{% url 'logout' %}">logout</a>
      {% else %}
        <a href="{% url 'login' %}">login</a> / <a href="{% url 'signup' %}">signup</a> #<----- here it encounters error
      {% endif %}
      <hr>
    </header>
    <main>
        <h2>Sign up</h2>
  <form method="post">
    {% csrf_token %}
    {% for field in form %}
      <p>
        {{ field.label_tag }}<br>
        {{ field }}
        {% if field.help_text %}
          <small style="color: grey">{{ field.help_text }}</small>
        {% endif %}
        {% for error in field.errors %}
          <p style="color: red">{{ error }}</p>
        {% endfor %}
      </p>
    {% endfor %}
    <button type="submit">Sign up</button>
  </form>
    </main>
  </body>
</html>

标签: pythondjango

解决方案


您需要在 urls.py 中指定登录和注销视图的名称

urlpatterns = [
    # rest of your URL configs
    path('login/', auth_views.LoginView.as_view(template_name='login/login.html', redirect_field_name='index'),
         name='login'),
    path('logout', auth_views.LogoutView.as_view(template_name='logout/logout.html', next_page='index'),
         name='logout'),
]

推荐阅读