2015-04-15 31 views
0

我正在使用django處理API。我想以下列方式訪問我的資源: {base_url}/employee/{emp_id}如何在python django中訪問url部分?

這裏emp_id不是GET參數。我如何在我的視圖中訪問此參數?有沒有任何標準的方式來訪問它,而無需手動解析URL?

+2

您是否閱讀過[URL調度器](https://docs.djangoproject.com/en/1.8/topics/http/urls/)上的文檔?這是一個很好的開始,詳細解釋了這一點。 – knbk

+0

這是很好的鏈接!謝謝!這是否意味着我需要編寫不同的函數來處理不同的請求? – SaurabhJinturkar

+1

這通常是如何完成的,除非處理不同的請求本質上是相同的,保存一些參數。將不同的url模式映射到單個視圖函數很容易。 – knbk

回答

1

根據您是使用基於類的視圖還是使用標準視圖函數,方法是不同的。

對於基於類的視圖,根據您願意執行的操作(ListView,DetailView,...),通常不需要解析url,而只需要在urls.py中指定參數的名稱或直接在類定義中的參數名稱。

基於類的觀點

urls.py

from mysite.employee.views import EmployeeView 

urlpatterns = patterns('', 
    ... 
    url(r'^employee/(?P<pk>[\d]+)/$', EmployeeView.as_view(), name='employee-detail'), 
    ... 
) 

員工/ views.py

class EmployeeView(DetailView): 
    model = YourEmployeeModel 
    template_name = 'employee/detail.html' 

請閱讀knbk指出你的文檔您需要導入DetailView

就這樣,你會得到你的員工取決於給出的pk參數。如果它不存在,則會拋出404錯誤。


基於函數看法它是在一個類似的方式完成:

urls.py

from mysite.employee.views import EmployeeView 

urlpatterns = patterns('', 
    ... 
    url(r'^employee/(?P<pk>[\d]+)/$', 'mysite.employee.views.employee_detail', name='employee-detail'), 
    ... 
) 

員工/ views.py

from django.shortcuts import get_object_or_404 

def employee_detail(request, pk): 
""" the name of the argument in the function is the 
    name of the regex group in the urls.py 
    here: 'pk' 
""" 
    employee = get_object_or_404(YourEmployeeModel, pk=pk) 

    # here you can replace this by anything 
    return HttpResponse(employee) 

我希望這有助於

+0

這是否回答你的問題?馬克解決了,如果它請 – tgdn