Django url - view - template NOTE

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:







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值