How to access url part in python django?

懵懂的女人 提交于 2019-12-12 04:48:35

问题


I am working on APIs using django. I want to access my resources in following way: {base_url}/employee/{emp_id}.

Here emp_id is not a GET parameter. How can I access this parameter in my view? Is there any standard way to access it without manually parsing URL?


回答1:


Depending on whether you are using class based views or whether you are using standard view functions the method is different.

For class based views, depending on which action you are willing to perform (ListView, DetailView, ...) usually you do not need to parse the url but only to specify the name of the argument in your urls.py or the name of the argument directly inside the class definition.

Class based views

urls.py

from mysite.employee.views import EmployeeView

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

employee/views.py

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

Please read the doc that knbk pointed out to you as you need to import DetailView

And as simply as that, you will get your employee depending on the pk argument given. If it does not exist a 404 error will be thrown.


In function based views it is done in a similar way:

urls.py

from mysite.employee.views import EmployeeView

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

employee/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)

I hope this helps



来源:https://stackoverflow.com/questions/29661986/how-to-access-url-part-in-python-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!