如何在Django中的/修复NoReverseMatch

时间:2019-12-04 05:19:21

标签: django

我要修复此错误:

NoReverseMatch at /
Reverse for 'register' not found. 'register' is not a valid view function or pattern name.
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 2.2
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'register' not found. 'register' is not a valid view function or pattern name.
Exception Location: C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 660
Python Executable:  C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\python.exe
Python Version: 3.7.0
Python Path:    
['D:\\Learning\\Work\\Djngo\\todo_app',
 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32',
 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages']
Server time:    Wed, 4 Dec 2019 05:07:28 +0000

在这一行中我遇到了错误:

<li class="nav-item">
        <a class="nav-link" href="{% url 'register' %}">Signup</a>
</li>

当我看到用户是否已登录并且如果他键入此URL http://127.0.0.1:8000/accounts/register时,他也可以转到注册页面,因此我不需要该页面

所以这就是为什么我将if语句添加到urls.py中的原因:

from django.urls import path
from django.contrib.auth.models import User
from todo import views
from django.contrib.auth.views import LoginView, LogoutView

if User.is_authenticated:
    urlpatterns = [
        path('',views.index,name='index'),
        path('accounts/logout/', LogoutView.as_view(), name='logout'),
    ]   
else:
    urlpatterns = [
        path('',views.index,name='index'),
        path('accounts/register',views.signup,name='register'),
        path('accounts/login/', LoginView.as_view(), {'template_name': 'registration/login.html'}, name='login'),
    ]   

但是当我添加此错误时,我会收到该错误,请帮助我!

错误屏幕截图:

enter image description here

这是我的观点。py

def login_user(request, template_name='registration/login.html', extra_context=None):  
    cap = None
    reg2 = None
    ###############################
    if requests.method == 'POST':
        recaptcha_response = requests.POST.get('g-recaptcha-response')
        url = 'https://www.google.com/recaptcha/api/siteverify'
        values = {
            'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
            'response': recaptcha_response
        }
        data = urllib.parse.urlencode(values).encode()
        req =  urllib.request.Request(url, data=data)
        response = urllib.request.urlopen(req)
        result = json.loads(response.read().decode())
        ''' End reCAPTCHA validation '''

        if result['success']:
            cap = True
        else:
            cap = False


    return render(requests,'login.html',{'cap':cap,})


# Create your views here.
def index(requests):
    return render(requests,'index.html')

def signup(requests):
    cap = None
    reg2 = None
    ###############################
    if requests.method == 'POST':
        reg = register(requests.POST)


        recaptcha_response = requests.POST.get('g-recaptcha-response')
        url = 'https://www.google.com/recaptcha/api/siteverify'
        values = {
            'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
            'response': recaptcha_response
        }
        data = urllib.parse.urlencode(values).encode()
        req =  urllib.request.Request(url, data=data)
        response = urllib.request.urlopen(req)
        result = json.loads(response.read().decode())
        ''' End reCAPTCHA validation '''

        if result['success']:
            cap = True
            if reg.is_valid():
                if cap == True:
                    user = reg.save(commit=False)
                    user.set_password(User)
                    user.save()
                    reg2 = True

            else:
                print(reg.errors)


        else:
            cap = False

    else:
        reg = register()

    return render(requests,'signup.html',{'reg':reg,'cap':cap,'reg2':reg2,})

这是我的 base.html

<!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="{% static 'css/custom/style.css' %}">
    <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js">
    <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
          <a class="navbar-brand" href="{% url 'index' %}">TODO</a>
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarText">
            <ul class="navbar-nav mr-auto">
              <li class="nav-item active">
                <a class="nav-link" href="{% url 'index' %}">Home <span class="sr-only">(current)</span></a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">New Task</a>
              </li>    
            </ul>
            {% if request.user.is_authenticated %}
                <ul class="navbar-nav nav-right">
                    <li class="nav-item">
                        <a class="nav-link" href="#">Profile</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{% url 'logout' %}">Logout</a>
                    </li>
                    <li class="nav-item">
                      <a class="nav-link" href="#">welcome: {{request.user}}</a>
                    </li>     
                </ul>
            {% else %}
                <ul class="navbar-nav nav-right">
                    <li class="nav-item">
                        <a class="nav-link" href="{% url 'register' %}">Signup</a>
                    </li>
                    <li class="nav-item">
                      <a class="nav-link" href="{% url 'login' %}">Login</a>
                    </li>     
                </ul>
            {% endif %}
          </div>
      </div>
    </nav>
    <script src="https://www.google.com/recaptcha/api.js?render=_reCAPTCHA_site_key"></script>
    {% block content_block %}
    {% endblock %}
</body>
</html>

错误在我的base.html中!

2 个答案:

答案 0 :(得分:1)

从您的网址中删除if-else条件,并在注册视图中检查用户是否已通过身份验证。如果用户已通过身份验证,则将用户重定向到其他URL。在这里,用户将被重定向到索引页面。

urls.py

from django.urls import path
from django.contrib.auth.models import User
from todo import views
from django.contrib.auth.views import LoginView, LogoutView

    urlpatterns = [
        path('',views.index,name='index'),
        path('accounts/logout/', LogoutView.as_view(), name='logout'),
        path('',views.index,name='index'),
        path('accounts/register',views.signup,name='register'),
        path('accounts/login/', LoginView.as_view(), {'template_name': 'registration/login.html'}, name='login'),
    ]

views.py

from django.shortcuts import redirect
from django.urls import reverse


def signup(requests):
    if requests.user.is_authenticated:
        return redirect(reverse('index'))

    cap = None
    reg2 = None
    ###############################
    if requests.method == 'POST':
        reg = register(requests.POST)


        recaptcha_response = requests.POST.get('g-recaptcha-response')
        url = 'https://www.google.com/recaptcha/api/siteverify'
        values = {
            'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
            'response': recaptcha_response
        }
        data = urllib.parse.urlencode(values).encode()
        req =  urllib.request.Request(url, data=data)
        response = urllib.request.urlopen(req)
        result = json.loads(response.read().decode())
        ''' End reCAPTCHA validation '''

        if result['success']:
            cap = True
            if reg.is_valid():
                if cap == True:
                    user = reg.save(commit=False)
                    user.set_password(User)
                    user.save()
                    reg2 = True

            else:
                print(reg.errors)


        else:
            cap = False

    else:
        reg = register()

    return render(requests,'signup.html',{'reg':reg,'cap':cap,'reg2':reg2,})

文档:reverseredirect

答案 1 :(得分:0)

您遇到此问题的原因是,根据urlpatterns是否经过验证,您拥有不同的User。拥有用户身份验证后,您将没有register网址名称,因此网址解析会出错。

要解决此问题并阻止用户访问这些页面的正确方法是进行两项更改:

在django contrib auth视图中设置redirect_authenticated_user。仅凭注销视图就可以了,因为它对auth用户和auth用户均无效。
urls.py

from django.urls import path
from django.contrib.auth.models import User
from todo import views
from django.contrib.auth.views import LoginView, LogoutView

urlpatterns = [
    path('',views.index,name='index'),
    path('accounts/logout/', LogoutView.as_view(), name='logout'),
    path('accounts/register',views.signup,name='register'),
    path('accounts/login/', LoginView.as_view(redirect_authenticated_user=True), {'template_name': 'registration/login.html'}, name='login'),
]   

在您自己的视图中重定向用户:
views.py:

def signup(requests):
    if requests.user.is_authenticated:
        return redirect(reverse('index'))
    # ...