如何在django中设置url以防止类似的工作?

时间:2014-09-19 05:15:10

标签: python django

我练习如何用django写一个网站
我用型号名称= Traveltime
完成了一个 但我还有很多工作要做(如:aaaaa,bbbbb,ccccc) 他们做类似的工作,只是模型名称不同

我觉得它重复,不知道该怎么做 我该怎么编辑我的urls.py ??请帮帮我谢谢!

urls.py:

urlpatterns = patterns('',
    url(r'^travel/$', views.object_list, {'model': models.Traveltime}),
    url(r'^travel/result/$', views.object_result, {'model': models.Traveltime}),
    url(r'^travel/update/$', views.update),
    #I have many urls to set (below)
    url(r'^aaaaa/$', views.object_list, {'model': models.aaaaa}),
    url(r'^aaaaa/result/$', views.object_result, {'model': models.aaaaa}),
    url(r'^aaaaa/update/$', views.update),
    url(r'^bbbbb/$', views.object_list, {'model': models.bbbbb}),
    url(r'^bbbbb/result/$', views.object_result, {'model': models.bbbbb}),
    url(r'^bbbbb/update/$', views.update),
    url(r'^ccccc/$', views.object_list, {'model': models.ccccc}),
    url(r'^ccccc/result/$', views.object_result, {'model': models.ccccc}),
    url(r'^ccccc/update/$', views.ccccc),

views.py

def object_list(request, model):
    obj_list = model.objects.filter(image_elect='')   
    paginator = Paginator(obj_list, 10)
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        contacts = paginator.page(1)
    except EmptyPage:
        contacts = paginator.page(paginator.num_pages)
    template_name = 'filterimgs/%s_list.html' % model.__name__.lower()
    return render_to_response(template_name, {'object_list': obj_list,"contacts": contacts},
                          context_instance=RequestContext(request))

def update(request):
    travel = Traveltime.objects.filter(title=request.POST['title'])
    # travel.update(image_elect='asd')
    return redirect(object_result)

def object_result(request, model):
    obj_list = model.objects.all()
    paginator = Paginator(obj_list, 10)
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger: 
        contacts = paginator.page(1)
    except EmptyPage:
        contacts = paginator.page(paginator.num_pages)
    template_name = 'filterimgs/%s_result.html' % model.__name__.lower()
    return render_to_response(template_name, {'object_list': obj_list,"contacts": contacts},
                          context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:0)

Django url模式是正则表达式,任何分组表达式都将作为附加参数传递到适当的视图中。

urlpatterns = patterns('',
    url(r'^([a-zA-Z]+)/$', views.object_list),
    url(r'^([a-zA-Z]+)/result/$', views.object_result),
    url(r'^([a-zA-Z]+)/update/$', views.update),
)

然后在您的请求中,您可以

import importlib

def object_list(request, model_type):
    # use the model_type which is passed in from 
    # the URL to actually grab the proper model
    found = importlib.import_module('models.{0}'.format(model_type))

Python足够优雅,允许您使用字符串导入模块。

此外,发现是一个蹩脚的名称,因此您应根据其目的而相应地命名。