我刚刚开始使用Django,我遇到了一些困难。 当我第一次加载" localhost:8000 / first_app"它成功加载index(),但点击"关于"链接,网址正在更改为" localhost:8000 / first_app / about /",但它仍在加载" index()"而不是"关于()"。不知道我错过了什么。
这是我的项目网址:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^first_app/', include('first_app.urls')),
)
应用网址:
from django.conf.urls import patterns, url
from first_app import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^about/', views.index, name='about'),
)
和views.py:
from django.http import HttpResponse
def index(request):
return HttpResponse("Rango says: Hello world! <br/> <a href='/first_app/about'>About</a>")
def about(request):
return HttpResponse("This is the ABOUT page! <br /> <a href='/first_app/'>Index</a>")
我使用的是Django 1.7和python 2.7。 感谢。
答案 0 :(得分:1)
您需要像这样定义您的网址;
urlpatterns = patterns('',
url(r'^about/$', views.about, name='about'),
url(r'^/$', views.index, name='index'),
)
基本上'^$'
是开始&amp;比赛结束。 ^
是模式的开始&amp; $
是模式的结尾,因此在定义网址时请记住这一点。最好使用$
来结束您的网址,以避免在您的模式中匹配的内容后,无论您添加到网址中的内容如何都会呈现视图。