2012-10-16 31 views
15

我是django的新手,我還在學習的東西之一是url_patterns。我設置了一個頁面應用程序來處理根路徑(http://www.mysite.com)以及一些靜態頁面,例如about頁面。我想出瞭如何爲根路徑設置url模式,但我無法讓站點將路徑'/ about'指向頁面「about」視圖。在Django中,你如何爲'/'和其他根目錄的url編寫url模式

這裏是我的主urls.py

from django.conf.urls import patterns, include, url 
from django.conf import settings 
urlpatterns = patterns('', 
    url(r'^polls/', include('polls.urls')), 
    url(r'^$', 'pages.views.root'), 
    url(r'^/', include('pages.urls')), 
) 

這裏是我的網頁的urls.py

from django.conf.urls import patterns, include, url 
urlpatterns = patterns('pages.views', 
     url(r'^about', 'about'), 
) 

,這裏是我的網頁的views.py

# Create your views here. 
from django.shortcuts import render_to_response 
from django.template import RequestContext 
from django.http import HttpResponse, HttpResponseRedirect 
from django.core.urlresolvers import reverse 

def root(request): 
    return render_to_response('pages/root.html',context_instance=RequestContext(request)) 
def about(request): 
    return render_to_response('pages/about.html',context_instance=RequestContext(request)) 

如果我改變主urls.py文件具有r'^a/', include('pages.urls')然後路徑'/一/關於'指向關於行動..所以我認爲它必須是一個問題我在這個文件中寫入URL模式的方式。但是,我無法弄清楚如何改變它。誰能幫忙?

+0

人民投票來關閉這個問題,你會不會介意成爲更具建設性和評論,讓我知道什麼指導方針沒有得到滿足,和/或我如何編輯這個問題以更好地滿足這些要求? – jay

回答

25

找出問題是什麼。在項目層面的正確url_pattern是:

urlpatterns = patterns('', 
    url(r'^polls/', include('polls.urls')), 
    url(r'^$', 'pages.views.root'), 
    url(r'', include('pages.urls')), 
) 

當這是在地方,「/約」和其他簡單直接的路徑正確。

謝謝大家!

+0

我想爲所有錯過它的人添加:'pages'是OP項目中的應用程序,而不是Django特定的語法。它可能是'other_pages'或類似的東西。 –

5

試試這個,對於url.py在項目層面:

urlpatterns = patterns('', 
# Examples: 
url(r'^$', 'apps_name.views.home', name='home'), 

# Uncomment the admin/doc line below to enable admin documentation: 
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')), 

# Uncomment the next line to enable the admin: 
url(r'^admin/', include(admin.site.urls)), 

(r'^about/', include('about.urls')), 
) 

,然後url.py的應用程序有關

urlpatterns = patterns('', 
    url(r'^$', direct_to_template, {"template": "about/about.html"}, name="about"), 
) 

要考慮到正則表達式是從頂部評估到底部,那麼如果路徑符合正則表達式,它將進入。要了解更多關於正則表達式谷歌它或嘗試偉大的書從Zed Shaw約regexps

1

注意,從Django的2.0版本的URL模式已改爲使用django.urls.path()入住這裏的例子:link

from django.urls import path 

from . import views 

urlpatterns = [ 
    # ex: /polls/ 
    path('', views.index, name='index'), 
    # ex: /polls/5/ 
    path('<int:question_id>/', views.detail, name='detail'), 
    # ex: /polls/5/results/ 
    path('<int:question_id>/results/', views.results, name='results'), 
    # ex: /polls/5/vote/ 
    path('<int:question_id>/vote/', views.vote, name='vote'), 
]