網路科技

Django (1)

FB公開社團 Larry的午茶時光
加入不需審核,歡迎讀者加入~
我的IG帳號: larry.time.taste。剛剛起步,歡迎大家追蹤~

https://docs.djangoproject.com/en/1.6/intro/tutorial03/

1. 如何將 url 部分當參數傳給 views.py?

urls.py 中 url 正規表示式要下參數
ex: r’^(?P<poll_id>d+)/results/$’

2. views.py return 方式:
return HttpResponse(“…”)  or
raise Http404

3. HttpResponse shortcut
return render(request, ‘polls/index.html’, context)

4. raise Http404 的 shortcut
original
try:
    poll = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
    raise Http404
return render(request, 'polls/detail.html', {'poll': poll})

shortcut

poll = get_object_or_404(Poll, pk=poll_id)
return render(request, 'polls/detail.html', {'poll': poll})

where pk is primary key.

其中 {‘poll’: poll} 為 variable name to variable value map.

為了釐清, 暫時改為 {‘poll’: poll1}. 在 html 中使用 {{ poll.id }} 或 {% … poll.id … %} 會將 poll1 object 帶入.

5. Removing hardcoded URLs in templates
original

<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>

modified

<li><a href="{% url 'detail' poll.id %}">{{ poll.question }}</a></li>
此行會去找 urls.py 中 name='detail’ 的 url view handler pair.

6. Namespacing URL names
urlpatterns = patterns('', 
    url(r'^polls/', include('polls.urls', namespace="polls")), 
    url(r'^admin/', include(admin.site.urls)), 
)
所以在第5點下 url 時就變成
<li><a href="{% url 'polls:detail' poll.id %}">{{ poll.question }}</a></li>
這樣可以讓負責 template 的 programmer 明確知道他要 call 哪一支app的哪一個view. 同時避免 view name 在不同 app 有衝突的情況, 但是還是主要是讓 template programmer 明確知道, naming ambiguity 自然就不存在了.

FB公開社團 Larry的午茶時光
加入不需審核,歡迎讀者加入~
我的IG帳號: larry.time.taste。剛剛起步,歡迎大家追蹤~

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *