2014-01-20 181 views
28

我在django 1.6(和python 2.7)中做了一個簡單的登錄應用程序,並且在開始時出現錯誤,導致我不能繼續。Django NoReverseMatch

這是該網站的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)), 
) 

這是登錄/ 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'), 
) 

這是登錄/人次,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') 

我有以此爲動作的表格:

{% url 'login:auth' %} 

而這正是問題是,當我嘗試加載頁面時,我得到:

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

但如果我URL模式設置爲

url(r'', views.auth, name='auth') 

它只是正常工作,它將操作設置爲'/'。

我一直在尋找答案,我不明白爲什麼它不起作用。 (r'^ login/$',include('login.urls',namespace ='login')),它沒有改變任何東西。

+0

可能重複[什麼是NoReverseMatch錯誤,以及如何解決它?](http://stackoverflow.com/questions/38390177/what-is-a-noreversematch-error-and-how-do- i-fix-it) – Sayse

回答

41

問題在於你在auth URL中包含主要URL的方式。 因爲您同時使用^和$,只有空字符串匹配。放下$。

+6

我簡直不敢相信那是那麼簡單,我把頭髮拉出來。謝謝! – freakrho

+1

謝謝,這個答案讓我至少有一個小時的絕望:) – maddob

+0

他們應該修復這個問題或者創建一個更好的錯誤信息。我花了20分鐘試圖弄清楚WTF出錯了。 – DataMania