Django实战(4):scaffold生成物分析

上一节用一个插件生成了类似rails的scaffold,其实无非就是URLconf+MTV。让我们看看具体都生成了哪些东西。
首先是“入口”的定义即URLconf,打开urls.py:

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

from depot.views import hello



urlpatterns = patterns('',

     url(r'^hello/ hello),

)

urlpatterns += patterns ('',

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

)

 

上面的代码中增加的配置行表示:以depotapp开头的url由depotapp/urls.py文件进行处理。

django的url配置中,除了(正则表达式,view函数)的方式外,还支持(正则表达式,include文件)的方式。通常把app自身相关的url写到自己的url配置文件中,然后在project中引用。

接下来看一下生成的depotapp/urls.py的内容:

from django.conf.urls.defaults import *

from models import *

from views import *



urlpatterns = patterns('',

    (r'product/create/$', create_product),

    (r'product/list/$', list_product ),

    (r'product/edit/(?P[^/]+)/$', edit_product),

    (r'product/view/(?P[^/]+)/$', view_product),

)

 

将CRU(没有D)的URL映射到了视图。而视图在depotapp/views.py中定义:

from django import forms

from django.template import RequestContext

from django.http import HttpResponse, HttpResponseRedirect

from django.template.loader import get_template

from django.core.paginator import Paginator

from django.core.urlresolvers import reverse



# app specific files



from models import *

from forms import *





def create_product(request):

    form = ProductForm(request.POST or None)

    if form.is_valid():

        form.save()

        form = ProductForm()



    t = get_template('depotapp/create_product.html')

    c = RequestContext(request,locals())

    return HttpResponse(t.render(c))







def list_product(request):

  

    list_items = Product.objects.all()

    paginator = Paginator(list_items ,10)





    try:

        page = int(request.GET.get('page', '1'))

    except ValueError:

        page = 1



    try:

        list_items = paginator.page(page)

    except :

        list_items = paginator.page(paginator.num_pages)



    t = get_template('depotapp/list_product.html')

    c = RequestContext(request,locals())

    return HttpResponse(t.render(c))







def view_product(request, id):

    product_instance = Product.objects.get(id = id)



    t=get_template('depotapp/view_product.html')

    c=RequestContext(request,locals())

    return HttpResponse(t.render(c))



def edit_product(request, id):



    product_instance = Product.objects.get(id=id)



    form = ProductForm(request.POST or None, instance = product_instance)



    if form.is_valid():

        form.save()



    t=get_template('depotapp/edit_product.html')

    c=RequestContext(request,locals())

    return HttpResponse(t.render(c))

 

视图中的相关内容比较多,主要的是模板,其次还有模型类、Paginator分页器、Form表单等等。

基本涵盖了典型的web应用交互的内容。

你可能感兴趣的:(django)