提问者:小点点

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内部服务器错误,更准确地说,是抛出一个错误:

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),
]

我的UserSignUpurls.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')
]

我的用户注册视图。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')

注册。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>

共1个答案

匿名用户

您需要在URL中指定登录和注销视图的名称。派克

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'),
]