Django 404错误

时间:2014-09-01 01:15:46

标签: django django-views django-urls

我创建了两个网址,这两个网址都是相同的视图。一个产生404错误而另一个产生错误。

urls.py

from django.conf.urls import url
from playerteamstats import views

urlpatterns = [
    # e.g. /stats
    url(r'^$', views.stats_index, name='index'), #Renders page
    # e.g. /stats/player
    url(r'^player/$', views.stats_index, name='player'), #Throws 404 error
]

views.py

from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template import RequestContext
from playerteamstats.models import Player,Team

def stats_index(request):
    return render_to_response('stats_index.html')

urls.py(root)

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

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^fixtures/$', include('fixtures.urls')),
    url(r'^stats/$', include('playerteamstats.urls')),
    #User public profile
    url(r'^(?P<username_in_url>\w+)/$', 'fantasymatchday_1.views.public_profile'),
)

404错误 404 Error

它似乎与/stats匹配应用程序正常,但当我输入/stats/player时,它说它无法找到公共用户名,就好像它在根目录中查找它一样URL。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

尝试:

url(r'^player/$', views.stats_index, name='player'), #Renders page
# e.g. /stats/player
url(r'^$', views.stats_index, name='index''), #Throws 404 error

第二个网址是全部。 Django按顺序处理URL。您上面的代码只是点击了第一个网址。

答案 1 :(得分:0)

来自Django文档:

  

urlpatterns变量的语法: -

     

urlpatterns应该是一个Python列表,格式为django.conf.urls.patterns()函数返回的格式。始终使用patterns()来创建urlpatterns变量。

所以试着这样做:

urlpatterns = patterns('',
                url(r'^$', views.stats_index, name='index'),
                url(r'^player/$', views.stats_index, name='player'), 
               )

这应该可以解决问题。

请参阅:https://docs.djangoproject.com/en/1.7/topics/http/urls/