Django NoReverseMatch

fre*_*rho 29 python django python-2.7 django-1.6

我正在django 1.6(和python 2.7)中创建一个简单的登录应用程序,我在开始时遇到错误,不让我继续.

这是该网站的url.py

from django.conf.urls import patterns, include, url
from django.contrib import admin
import login

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', include('login.urls', namespace='login')),
    url(r'^admin/', include(admin.site.urls)),
)
Run Code Online (Sandbox Code Playgroud)

这是login/urls.py:

from django.conf.urls import patterns, url
from login import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^auth/', views.auth, name='auth'),
)
Run Code Online (Sandbox Code Playgroud)

这是登录/视图,py

from django.shortcuts import render
from django.contrib.auth import authenticate

def auth(request):
    user = authenticate(username=request.POST['username'], password=request.POST['password'])
    if user is not None:
        # the password verified for the user
        if user.is_active:
            msg = "User is valid, active and authenticated"
        else:
            msg = "The password is valid, but the account has been disabled!"
    else:
        # the authentication system was unable to verify the username and password
        msg = "The username and password were incorrect."
    return render(request, 'login/authenticate.html', {'MESSAGE': msg})

def index(request):
    return render(request, 'login/login_form.html')
Run Code Online (Sandbox Code Playgroud)

我有一个表单,其中包含此操作:

{% url 'login:auth' %}
Run Code Online (Sandbox Code Playgroud)

这就是问题所在,当我尝试加载页面时,我得到:

Reverse for 'auth' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'$auth/']
Run Code Online (Sandbox Code Playgroud)

但是如果我将url模式设置为

url(r'', views.auth, name='auth')
Run Code Online (Sandbox Code Playgroud)

它工作正常,只有它将动作设置为'/'.

我一直在寻找答案,我不明白为什么它不起作用.

我尝试将登录URL模式更改为url(r'^ login/$',include('login.urls',namespace ='login')),并且它没有改变任何内容.

Dan*_*man 43

问题在于您在主要URL中包含auth URL的方式.因为你同时使用^和$,所以只有空字符串匹配.放弃$.

  • 我简直不敢相信,我把头发拉了出来.谢谢! (6认同)