2011-04-13 23 views
1

如果我想讓django應用程序叫做app1,它可以使用戶發佈便箋到某人的頁面和他/她自己的頁面。 如果用戶已登錄,則不需要在url中使用用戶名,但url中的username參數可以作爲urlconf中的父級。django問題:在父urlconf中捕獲的參數,incude()和反向匹配

要清楚:
urls.py

urlpatterns = patterns('' 

    #if registered user/anonymous user visit someone's page 
    url(r'^/foo/users/(?P<username>\w+)/app1/',include('app1.urls', namespace='myapp1')), 

    #if user is logged in in his own page 
    url(r'^app1/', include('app1.urls', namespace='myapp1')), 
    ... 
) 

APP1/urls.py

urlpatterns = patterns('', 
    # I expect this pattern receives the username parameter from above 
    url(r'^note/add/$', app1_views.add_note, 
    name='add_note'), 

    url(r'^note/add/$', app1_views.add_note, 
    { 'username':None}, name='add_note_own'), 
    ... 
    ...  
)  

APP1/views.py

def add_note(request, username=None): 
    ... 
    ... 

第一個問題
現在例如約翰登錄和傑克的筆記頁約翰想發佈一個筆記。
我希望能夠做這樣的事或接近這樣的事情:

模板APP1/notes.html

{% if request.user.is_authenticated %} 
    {%if in his/her own note page %} 
     <a href="{% url add_note_own %}">add note</a> Expected generated url: www.domain.com/app1/add 
    {%else} 
     <a href="{ %url add_note %}">add note</a> Expected generated url: www.domain.com/foo/jack/app1/add 
    {%endif%} 
{% endif %} 

這可能嗎?

另一件事,
如果約翰在傑克的頁面寫筆記,和Django的給音符ID == 3,
所以顯示這一點,只有這些URL是有效的:
www.example.com/foo /插孔/ APP1/3
www.example.com/foo/app1/3(如果傑克登錄)

第二個問題:
我想要實現的是反向匹配可以接受參數捕捉爲到include()涉及到你的父urlconf到 rl配置。 可以這樣做嗎?

或者如果你明白我的意思,並可以提供更簡單的解決方案,請這樣做:)
對不起,如果這篇文章令人困惑,我很困惑自己。 非常感謝耐心。

我使用Django 1.2.5

回答

0

你需要傳遞一個用戶名,一個例子可以是:

urlpatterns = patterns('', 
    # I expect this pattern receives the username parameter from above 
    url(r'^note/add/(?P<username>[^/]+)/$', app1_views.add_note, name='add_note'), 

    # username is an optional argument, so no need to pass it 
    url(r'^note/add/$', app1_views.add_note, name='add_note_own'), 
) 

,然後在模板:

{% if request.user.is_authenticated %} 
    {% if page.owner == request.user %} 
     <a href="{% url add_note_own %}">add note</a> 
    {% else %} 
     <a href="{% url add_note request.user.username %}">add note to {{ request.user.username }}</a> 
    {% endif %} 
{% endif %}