您的位置:首页 > 编程语言 > Go语言

Django url - view - template NOTE

2013-08-02 12:35 190 查看
Project: fruit

App: apple

1. url -- view:

fruit/urls.py:

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

urlpatterns = patterns('',
url(r'^apple/', include('apple.urls')),
)


This map url: "apple/*the-rest*" and dispatch "*the-rest*" to apple/urls.py:

from django.conf.urls import patterns, url
from apple import views

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


Here we try to match with *the-rest* part of url with pattern, which is '^$' here and only empty part can be matched.

To accept more urls:

urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<inst_id>\d+)/$', views.detail, name='detail')
)


The second pattern matches localhost:port/apple/*inst_id*/ *inst_id* is any number.

In the above code, each pattern is mapped with a function in view: view.index, view.detail.

from django.http import HttpResponse

def index(request):
txt = 'This is index.'
return HttpResponse(txt)

def detail(request, inst_id):
txt = 'This is detail of inst:%s' % inst_id
return HttpResponse(txt)


2. view - template:

The mapper function need to return a HttpResponse to the browser.

It can be a hard coded html file.

Better way to do that is to pass the data to template and render the template.

1. create a directory apple/templates/apple

2. create apple/templates/apple/index.html

{% if inst_list %}
<ul>
{% for inst in inst_list %}
<li><a href="/apple/{{ inst.id }}/">{{ inst.name }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No insts are available.</p>
{% endif %}
3. use the template in the view:

from django.template import RequestContext, loader

class Instance(object):
def __init__(self, _id, name):
self.id = _id
self.name = name

def index(request):
inst1 = Instance(1, 'fuji')
inst2 = Instance(2, 'gala')
inst3 = Instance(3, 'red')
inst_list = [inst1, inst2, inst3]
template = loader.get_template('apple/index.html')
context = RequestContext(request, {
'inst_list':inst_list,
})
return HttpResponse(template.render(context))

def detail(request, inst_id):
txt = 'This is detail of inst:%s' % inst_id
return HttpResponse(txt)


4. view.index will render index.html template and return the following page.



Each item is linked to another url:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: